当我尝试将对象推送到MongoDB和Nodejs中的数组时,为什么会出现castError?

我有一个mongoDB,我试图让一个Nodejs服务器来操纵数据库中的数据。 当我尝试将评论推送到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中的错误: 邮递员屏幕

帮助将不胜感激!

  1. 首先确保你在req.body中收到了什么,从req.body直接存储是不好的。
  2. 第二编号 注释架构方面一个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)) });