[英]Why do I get a castError when I try to push an object to an array in MongoDB and Nodejs?
I have a mongoDB and I am trying to make a Nodejs server to manipulate the data in the database. 我有一个mongoDB,我正在尝试制作一个Nodejs服务器来操纵数据库中的数据。 I get a castError when I try to push a Comment to the Comments array in a BlogPost object. 当我尝试将Comment推送到BlogPost对象中的Comments数组时,我得到一个castError。
Source code below, please tell me if you're missing important information. 下面的源代码,如果您缺少重要信息,请告诉我。 Thanks in advance! 提前致谢!
The route: 路线:
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)) });
The BlogPost schema: 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'
}]
});
The Comment schema: 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
});
Here is the error in postman: postman screen 这是邮递员中的错误: 邮递员屏幕
Help would be greatly appreciated! 帮助将不胜感激!
third why 2 queries for simple update. 第三,为什么2查询简单更新。 you can use $push, $addToSet to push directly to comments or $pull to remove from comments. 您可以使用$ 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))
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.