CastError:强制转换为ObjectId的值失败

时间:2020-05-10 00:16:28

标签: mongodb express mongoose mongodb-query

每次尝试检查if条件(project == null)时,我都会收到猫鼬错误。请参见下面的代码:

var IssueSchema= new Schema ({

    issue_description: {
        type: String,
        min: 5,
        max: 500,
        required: true

    },
    issue_status: {
        type: String,
        min: 5,
        max: 255,
        default: "Open"
    },
    issue_priority: {
        type: String,
        min: 5,
        max: 255
    },
    deadline:{
        type: Date
    },
},
    {timestamps:true});

var Project= new Schema ({
    name: {
        type: String,
        required: true,
        min: 5,
        max: 255

    },

    description: {
        type: String,
        min: 5,
        max: 500      
    },
    status: {
        type: String,
        min: 5,
        max: 255
    },
    priority: {
        type: String,
        min: 5,
        max: 255
    },
    progress: {
        type: String,
        min: 5,
        max: 255
    } , 
    issues: [IssueSchema],
    risks: [RiskSchema],
    _user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}, {timestamps:true});

代码:

控制器


        Project.findById({_id:req.params.projectId}, (err,project) => {
            console.log(project);
            if (project == null) {
              err= new ErrorHandler(404, "Project not found");
              return next (err);
            }   
             else {
                project.issues.push(req.body);
                project.save();
                res.status(200).send('Issue created');}

            }
        )};  

路由器

projectRouter.route ('/:projectId/issues')

.post(issueController.createIssue)

如果我输入正确的投影效果很好。但是我想处理指定的projectID不存在的情况。当我在URL参数中输入一些随机projectID时,它会抛出:UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "123" at path "_id" for model "Project"

有什么想法我做错了吗?

2 个答案:

答案 0 :(得分:0)

条件project== null并不是问题,在这种情况下,您的查询甚至没有从代码触发到数据库。

问题:

因此,猫鼬.findById()将采用有效的字符串值,并在内部将其转换为类型ObjectId()

如果您将字符串5eb78994dbb89024f04a2507传递给.findById(),则猫鼬内部会执行以下操作.findOne({_id : ObjectId('5eb78994dbb89024f04a2507')})

当我说 valid 字符串时,您需要了解ObjectId()内的字符串值必须具有某种形式,请检查以下内容:MongoDB-ObjectId

如果您传递的123不是ObjectId()猫鼬的有效字符串,如果未能转换为ObjectId()并甚至在形成查询之前就抛出该错误。

因此,要测试您的情况,如果您的实际字符串是这样的5eb78994dbb89024f04a2507,只需通过更改最后一个值(例如5eb78994dbb89024f04a2508)来对其进行调整,然后尝试一下,或者您可以从上面提供的链接中获取示例或您数据库中其他馆藏的文档。

答案 1 :(得分:0)

我遇到了同样的问题,所以我将 findByIdandUpdate 替换为 findOneAndUpdate

替换以下代码

Profile.findByIdAndUpdate  (
          { user: req.user.id },
          { $set: profileFields },
          { new: true }
        ) .then((profile) => res.json(profile))
      .catch((err) => console.log(err));

Profile.findOneAndUpdate(
          { user: req.user.id },
          { $set: profileFields },
          { new: true }
        ) .then((profile) => res.json(profile))
      .catch((err) => console.log(err));

作品魅力