【发布时间】:2019-10-10 07:32:45
【问题描述】:
Comments 是嵌套在 Post Schema 中的数组。我想通过将新评论推送到 cmets 数组来更新相应的帖子。但出现错误:CastError: Cast to ObjectId failed for value "cmets" at path "_id" for model "post"
- 阅读相关帖子
- 尝试使用“mongoose.Types.ObjectId”,无效
- 猫鼬版 ^5.5.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”是我的“用户”架构的参考。不知道如何解决这个带有强制转换错误的嵌套问题。
【问题讨论】: