首页 > 解决方案 > MongooseError [CastError]:模型“User”的路径“_id”处的值“undefined”转换为 ObjectId 失败

问题描述

我正在使用 vue、express、mongodb 和 axios 开发一个项目,以便为用户页面提供 CRUD 功能。目前,我已经设置了当您单击单元格时它会更新数据库的位置。但是,当我尝试保存更改时,我的控制台中不断出现此错误:“MongooseError [CastError]: Cast to ObjectId failed for value “undefined” at path “_id” for model “User”” 没有数据记录在我的控制台也来自我的“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);
          }
      })

标签: javascriptmongodbexpressvue.jsaxios

解决方案


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

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

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


推荐阅读