模型“ post”的路径“ _id”的值“ comments”的强制转换为ObjectId

时间:2019-05-23 17:12:06

标签: mongodb express mongoose

Comments是嵌套在Post Schema中的数组。我想通过将新评论推送到comments数组来更新相应的帖子。但出现错误:CastError:模型“ post”的路径“ _id”的值“ comments”的Cast失败,投射到ObjectId

  1. 阅读相关帖子
  2. 试图使用“ mongoose.Types.ObjectId”,没有用
  3. 猫鼬版本^ 5.5.4
  4. 我在此处使用的所有ID均有效
const PostSchema = new Schema({
    ...
    comments: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'user',
            },
            body: {
                type: String,
                required: [true, 'Content required'],
            },
        }
    ],
   ...
});
PostRouter.put('/posts/comments', (req, res) => {
    const { id } = req.query;
    const userID = req.body.user;
    const body = req.body.body;
    const comment = {
        user: userID,
        body: body,
    };

    Posts
        .update({ _id: id }, { $push: { comments: comment }})
        .then(result => {
            res.status(200).json(result.ok);
        })
        .catch(err => console.log(err));
});

我有一个类似的例子:在用户模式“ friends”数组中添加一个“ friendID”。如预期般运作。

const senderID = req.query.sender;
const recipientID = req.query.recipient; 

Users .update({ _id: recipientID }, { $push: { friends: senderID }}) 
.then(result => res.status(200).json(result.ok)) 
.catch(err => console.log(err)); 

但是我尝试在此处添加的“注释”是一个对象,而不是有效的ID字符串。

我认为问题出在“ Comments”数组中,因为“ comment.user”是我的“ User”模式中的引用。不知道该如何解决带有投放错误的嵌套问题。

1 个答案:

答案 0 :(得分:1)

如果userID和_id是有效的mongodb _id,则

mongoose.Types.ObjectId 是多余的。

PostRouter.put('/posts/comments', (req, res) => {
const { id } = req.query;
const userID = req.body.user;
const body = req.body.body;
const comment = {
    user: userID,
    body: body,
};

Posts
    .update({ _id: id }, { $push: { comments: comment }})
    .then(result => {
        res.status(200).json(result.ok);
    })
    .catch(err => console.log(err));
});