【问题标题】:MongooseError [CastError]: Cast to ObjectId failed for value "undefined" at path "_id" for model "User"MongooseError [CastError]:模型“用户”的路径“_id”处的值“未定义”转换为 ObjectId 失败
【发布时间】:2020-07-31 16:24:20
【问题描述】:

我正在使用 vue、express、mongodb 和 axios 开发一个项目,以便为用户页面提供 CRUD 功能。目前,我已经设置了当您单击单元格时它会更新数据库的位置。但是,当我尝试保存更改时,我的控制台中不断出现此错误: “MongooseError [CastError]:模型“用户”的路径“_id”处的值“未定义”转换为 ObjectId 失败” 我的控制台也没有数据从我的“console.log(_id)”中记录,只有 {} undefined 被打印。 我还没有找到任何对我有帮助的东西。任何帮助将不胜感激。 这是我的 App.Vue

<template>
    <div id="nav">
      <router-link to="/">Home |</router-link>
      <router-link to="/edituser"> Add/Edit/Delete User</router-link>
      <router-view></router-view>
      <h3>List of Users</h3>
      <table id="table">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Email</th>
          <th>Password</th>
        </tr>
        </table>
    <div v-for="user in users" :key="user" class="userlist">
        <p :to="{query:{user: firstname}}" contenteditable>
            {{user.firstname}} 
        </p>
        <p :to="{query:{user: lastname}}" contenteditable>
            {{user.lastname}} 
        </p>
        <p :to="{query:{user: email}}" contenteditable>
            {{user.email}} 
        </p>
        <p :to="{query:{user: password}}" contenteditable>
            {{user.password}}
        </p>
    </div>
    <br>
    <button v-on:click="saveEdit">Save Changes</button>
    </div>
</template>

<script>
import UserService from "./UserService"
export default {
  name: "Navigation",
  data(){
    return{
    users: [],
    user: Object,
    userId: '',
    err: ''
    }
  },
  methods:{
    saveEdit(){
            try{
                this.user = UserService.updateUsers(this.user)
            } catch (err){
                this.error = err.message;
            }
    }
  },
     async created(){
      try{
        this.users = await UserService.getUsers();
      } catch(err){
        this.error = err.message;
      }
    }
}
</script>

这是我的 UsersService.js

    import axios from "axios";
    const mongoURL = "http://localhost:5000/api/posts";

        static updateUsers(user){
            const url = `${mongoURL}/update/${user._id}`
            console.log(url)

            return axios.put(url, {
                user,
            })
        }


    export default UserService;

Here is my Users.js model
const mongoose = require('mongoose');

const User = mongoose.model("User",{
    firstname: {
        type: String,
        required: true,
        trim: true
    },
    lastname: {
        type: String,
        required: true,
        trim: true
    },
    email: {
        type: String,
        required: true,
        trim: true
    },
    password: {
        type: String,
        required: true,
        trim: true
    }
})

module.exports = User;

这是我的posts.js

const express = require("express"),
      mongoose = require("mongoose"),
      User = require("../models/Users.js"),
      router = express.Router();

      router.put("/update/:id", async (req,res) =>{
          console.log(req.body);
          const user = new User(req.body["user"]);
          const _id = req.params.id;
          console.log(_id);
          console.log(req.body["user"]);
          const updateProperies = Object.keys(user);

          try{
              const editUser = await User.findByIdAndUpdate(_id,user,{
              });
              if (!editUser){
                  return res.status(404).send();
              }
              console.log(editUser);
              res.send(editUser);
          } catch (error) {
              console.log(error);
              res.status(400).send(error);
          }
      })

【问题讨论】:

    标签: javascript mongodb express vue.js axios


    【解决方案1】:

    我怀疑错误来自 try 部分。看下面的代码

                  const editUser = await User.findByIdAndUpdate(_id,user,{
    

    您不应该只使用_id,在这种情况下用户是多余的。当你删除它时会发生什么(,用户,)

    【讨论】:

    • 当我删除用户时,现在它给了我这个错误:原因:错误:传入的参数必须是 12 个字节的单个字符串或 24 个十六进制字符的字符串
    猜你喜欢
    • 2021-07-04
    • 2018-03-17
    • 2021-06-19
    • 2021-06-05
    • 2014-06-20
    • 2020-11-19
    • 2021-07-04
    • 2017-08-18
    • 2016-11-11
    相关资源
    最近更新 更多