我有一个 mongoDB,我正在尝试制作一个 Nodejs 服务器来操作数据库中的数据。当我尝试将 Comment 推送到 BlogPost 对象中的 Comments 数组时,出现了castError。
下面是源代码,如果您缺少重要信息,请告诉我。 提前致谢!
路线:
routes.post('/comments/push/:id', function(req, res) {
const blogPostId = req.param('id');
const commentProps = req.body;
BlogPost.findById(blogPostId)
.then((blogPost) => {
blogPost.comments.push(commentProps);
return blogPost.save();
})
.then((blogPost) => res.status(200).json({
'status': 'Comment is deleted.',
'comment': blogPost
}))
.catch((error) => res.status(400).json(error)) });
BlogPost 架构:
const BlogPostSchema = new Schema({
content: {
type: String,
validate: {
validator: (content) => content.length > 5,
message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
rating: Number,
user: { type: Schema.Types.ObjectId, ref: 'user' },
board: {type: Schema.Types.ObjectId, ref: 'board'},
comments: [{
type: Schema.Types.ObjectId,
ref: 'comment'
}]
});
评论架构:
const CommentSchema = new Schema({
content: {
type: String,
validate: {
validator: (content) => content.length > 5,
message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
user: { type: Schema.Types.ObjectId, ref: 'user' },
rating: Number
// board: Board
});
这是 postman 中的错误: postman screen
非常感谢您的帮助!
最佳答案
- 首先确保您在 req.body 中收到的是什么,这不好 直接从 req.body 存储。
- 第二个引用文献。注释 Schema 方面是 objectId,而 req.body 是 对象本身。我不确定你要做什么,但它 类似 blogPost.comments.push(req.body.someValidId);
第三个为什么 2 个查询用于简单更新。您可以使用 $push、$addToSet 直接推送到评论,或使用 $pull 从评论中删除。
BlogPost.findOneAndUpdate({
_id:blogPostId
}, {
$addToSet:{
comments : someValidId
}
}, {
new :true,
upsert:false
})
.then((blogPost) => {
res.status(200).json({
'status': 'Comment is deleted.',
'comment': blogPost
})
})
.catch((error) =>
res.status(400).json(error))
});
关于node.js - 当我尝试将对象推送到 MongoDB 和 Nodejs 中的数组时,为什么会出现castError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681039/