Comments是嵌套在Post Schema中的数组。我想通过将新评论推送到comments数组来更新相应的帖子。但出现错误:CastError:模型“ post”的路径“ _id”的值“ comments”的Cast失败,投射到ObjectId
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”模式中的引用。不知道该如何解决带有投放错误的嵌套问题。
答案 0 :(得分:1)
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));
});