如何在猫鼬中正确转换ObjectId

时间:2019-04-26 20:15:24

标签: javascript node.js mongodb express mongoose

使用猫鼬在express.js中转换ObjectId时遇到了一些问题。

在我的路线中,我之前尝试过铸造,也直接使用过req.params.id。似乎没有任何作用。我100%确定ID是正确的。我尝试创建一个新帖子,然后直接直接复制ID。

有什么想法为什么无法识别我的ObjectId?

我的模式:

let PostSchema = new Schema({
    _id: {type: mongoose.Schema.Types.ObjectId, auto: true},
    title: String,
    author: String,
    date: { type: Date, default: Date.now()},
    body: String,
    comments: [CommentSchema],
    upvotes: Number,
    downvotes: Number, 
});

我的路线:

app.post('/api/post/:id/comment', (req, res) => {
    let comment = new PostComment({
        author: req.body.author,
        body: req.body.body,
        date: req.body.date,
        upvotes: 0,
        downvotes: 0,
    })
    const id = mongoose.ObjectId.cast(req.params.id)
    Post.findOneAndUpdate(
        {_id: id},
        { $push: {comments: comment}}
        )
        .then(result => {
            if(!result) {
                res.sendStatus(404).send({
                    success: 'false',
                    message: 'Comment not added',
                });
            } else {
                res.status(200).json(result);
            }
        })
        .catch(err => console.log(err));
});

错误消息:

Cast to ObjectId failed for value "{ id: \'5cc3632db9e2405960e3ed0e\' }" at path "_id" for model "Post"

存在相同问题的其他路线

// get single post by id
app.get("/api/post/:id", (req, res) => {
    const id = req.params;
    Post.findById(id)
        .exec()
        .then(result => {
            if(!result) {
                res.sendStatus(404).send({
                    success: 'false',
                    message: 'No post found',
                });
            } else {
                res.status(200).json(result);
            }
        })
        .catch(err => console.log(err));

});

1 个答案:

答案 0 :(得分:1)

似乎您在SO上发布后便会自己找到答案,所以就到这里了。 此函数将有效地将字符串强制转换为ObjectId:mongoose.Types.ObjectId(req.params.id);