【问题标题】:Cast to ObjectId failed for value "comments" at path "_id" for model "post"对于模型“post”的路径“_id”中的值“comments”,转换为 ObjectId 失败
【发布时间】:2019-10-10 07:32:45
【问题描述】:

Comments 是嵌套在 Post Schema 中的数组。我想通过将新评论推送到 cmets 数组来更新相应的帖子。但出现错误:CastError: Cast to ObjectId failed for value "cmets" at path "_id" for model "post"

  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));
});

我有一个类似的:将“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”是我的“用户”架构的参考。不知道如何解决这个带有强制转换错误的嵌套问题。

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    mongoose.Types.ObjectId 如果 userID 和 _id 是有效的 mongodb _id 是多余的。

    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));
    });
    

    【讨论】:

    • 这是我的原始代码,但没有工作,得到了演员错误。然后我阅读了一些帖子并添加了“mongoose.Types.ObjectId”,就像上面的代码一样,但仍然不起作用,仍然抛出相同的错误。
    • 发现问题:我有另一个路径为“/:id”的“put”方法。这个路径是“/cmets”。删除第一个 put 方法后,我的代码就可以工作了。
    猜你喜欢
    • 2021-05-12
    • 2019-06-26
    • 1970-01-01
    • 2020-05-11
    • 2020-10-19
    • 2023-03-28
    • 2022-10-05
    • 2018-07-10
    • 2017-05-23
    相关资源
    最近更新 更多