首页 > 解决方案 > MongoDB - Mongoose,在嵌套查询中添加新文档数据

问题描述

我无法在嵌套查询中推送数据

我无法理解我在代码中遗漏了什么(我是 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 }} }     });

先感谢您

标签: node.jsmongodbmongoose

解决方案


$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符号。操作$set如下:

User.findByIdAndUpdate(req.user,
   { "set": { "posts.post.article": req.body.description  } } 
);

推荐阅读