node.js - MongoDB - Mongoose,在嵌套查询中添加新文档数据

标签 node.js 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 }} }     });

提前谢谢

最佳答案

<强> $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/

相关文章:

javascript - 单击菜单项机器人框架向机器人发送消息

node.js - Sequelize - 在关联表上选择

mongodb - 在 mac os 10.15 for php7 上安装 mongodb

node.js - BreezeJS RequireJS 针对生产进行了优化

php - Doctrine 2 ODM MongoDB 从内存中将图像存储在 GridFS 中

node.js - 按数组中的最后一项排序

javascript - 主键整数返回在查找时递增

javascript - 在 Node.js 中解析大型 XML 文件

javascript - 尝试在 find() 中使用 $near 查询时出错

node.js - 精益()里面填充 Mongoose