猿问

CastError:模型“”的路径“_id”处的值“未定义”转换为 ObjectId 失败

我正在尝试使用 MERN 堆栈制作一个应用程序。当我尝试将用户添加到当前数据库时,它返回“CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Project"我做错了什么?”


API.js


import axios from "axios";


export default {

  

  updateUser: function (id, data) {

    return axios.put("/api/user/" + id, data);

  },

}

apiRoute.js


app.put("/api/project/:id/add-user", async (req, res) => {

    // Find the project that was created and update it with a user

    // console.log("Hello")

    try {

      const dbProject = await db.Project.findOneAndUpdate({ _id: req.params.id }, {

        // Append the User to the Project object

        $push: { users: req.body.userId }

      }, { new: true });

      // Send the request back to the front end

      res.send(dbProject)


    } catch (error) {

      console.log({ "PUT - Project Add User": error })

      res.send(error)

    }

  });

项目.js(模型)


const mongoose = require('mongoose');

const { Schema } = mongoose;


const projectSchema = new Schema({

  project_name: {

    type: String,

    unique: true

  },

  team_lead: String,

  description: String,

  tags: String,

  location: String,

  num_members: Number,

  // image: String,

  users: [

    {

      type: Schema.Types.ObjectId,

      ref: "users"

    }

  ]

});


const Project = mongoose.model('Project', projectSchema);


module.exports = Project;


慕后森
浏览 104回答 1
1回答

开心每一天1111

你的错误非常明显出了什么问题。再读一遍:CastError:模型“Project”的路径“_id”处的值“未定义”转换为 ObjectId 失败undefined...路径“_id”失败...这意味着您的req.params.id,因为它位于字段/路径“_id”,所以未定义。检查您是否确实向路线发送了一些值。您从客户端向您的路线发送了错误的参数const dbProject = await db.Project.findOneAndUpdate({ _id: req.params.id }, {    // Append the User to the Project object    $push: { users: req.body.userId }  }, { new: true });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答