我无法在嵌套查询中推送数据
我无法理解我在代码中错过了什么(我是 mongodb 的新手,只是在尝试)
我的目标是在帖子中添加“帖子”
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
posts: {
post:{
title: String,
article: String,
comments: {}
}
}
});
const User = mongoose.model('userInfo', UserDetail, 'userInfo');
module.exports = User;
这是我的更新代码
User.findOneAndUpdate({_id: req.user._id},{ $push: {"posts": { "post" : { "article": req.body.description }} } });
提前谢谢
最佳答案
<强> $push
用于将指定值追加到数组中。如果要更新的文档中不存在该字段,则会添加以该值作为其元素的数组字段,但如果该字段不是数组,则操作将失败。在您的情况下 posts
是一个嵌入文档,而不是一个数组。
您可以更新架构以使 posts
成为数组:
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
posts: [
{
title: String,
article: String,
comments: []
}
]
})
然后进行推送
User.findByIdAndUpdate(req.user,
{ "$push": {
"posts": {
"article": req.body.description
}
} }
);
<小时/>
或使用 $set
与 dot notation如果使用现有架构。与 $set
的操作遵循以下示例:
User.findByIdAndUpdate(req.user,
{ "set": { "posts.post.article": req.body.description } }
);
关于node.js - MongoDB - Mongoose,在嵌套查询中添加新文档数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621146/