【问题标题】:Mongoose: CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model ""Mongoose:CastError:对于模型“”的路径“_id”处的值“未定义”,转换为 ObjectId 失败
【发布时间】:2021-03-13 01:52:00
【问题描述】:

我正在尝试使用 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)
    }
  });

project.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;

完整的错误消息:

 {
[0]   'PUT - Project Add User': CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Project"
[0]       at model.Query.exec (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:4358:21)
[0]       at model.Query.Query.then (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:4450:15)
[0]       at processTicksAndRejections (node:internal/process/task_queues:93:5) {
[0]     messageFormat: undefined,
[0]     stringValue: '"undefined"',
[0]     kind: 'ObjectId',
[0]     value: 'undefined',
[0]     path: '_id',
[0]     reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
[0]         at new ObjectID (/Users/tolit/Downloads/Co-Lab-master/node_modules/bson/lib/bson/objectid.js:59:11)
[0]         at castObjectId (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/cast/objectid.js:25:12)
[0]         at ObjectId.cast (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/schema/objectid.js:267:12)
[0]         at ObjectId.SchemaType.applySetters (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/schematype.js:1075:12)
[0]         at ObjectId.SchemaType._castForQuery (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/schematype.js:1510:15)
[0]         at ObjectId.SchemaType.castForQuery (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/schematype.js:1500:15)
[0]         at ObjectId.SchemaType.castForQueryWrapper (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/schematype.js:1477:20)
[0]         at cast (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/cast.js:331:32)
[0]         at model.Query.Query.cast (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:4759:12)
[0]         at castQuery (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:4559:18)
[0]         at model.Query.Query._findAndModify (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:3458:23)
[0]         at model.Query.<anonymous> (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/query.js:3028:8)
[0]         at model.Query._wrappedThunk [as _findOneAndUpdate] (/Users/tolit/Downloads/Co-Lab-master/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
[0]         at /Users/tolit/Downloads/Co-Lab-master/node_modules/kareem/index.js:369:33
[0]         at processTicksAndRejections (node:internal/process/task_queues:75:11)
[0]   }
[0] }

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您的错误非常明显,有什么问题。再读一遍:

    CastError:模型“Project”的路径“_id”处的值“undefined”转换为 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 });
    

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2021-05-12
      • 2019-06-26
      • 2021-06-02
      • 2018-03-17
      • 2023-03-28
      相关资源
      最近更新 更多