node.js - 如何在 Mongoose 查询对象中更新

标签 node.js mongodb mongoose

如果我单击 UI 中的批准按钮,我需要将特定评论的状态更改为 Y,我的文档结构如下。

     {
    "_id" : ObjectId("5a1fd0ffef39ff11ae353d10"),
    "file_name" : "Profile",
    "file_type" : "docx",
    "created_date" : ISODate("2017-11-28T10:29:10.373Z"),
    "updated_date" : ISODate("2017-11-28T12:39:32.148Z"),

    "comments" : [ 
        {
            "created_date" : ISODate("2017-11-28T13:23:51.472Z"),
            "status" : "N",
            "comment_text" : "Yes...",
            "username" : "Vishnu"
        }, 
        {
            "created_date" : ISODate("2017-11-28T13:24:15.938Z"),
            "status" : "N",
            "comment_text" : "Yes...",
            "username" : "Vishnu"
        }, 
        {
            "created_date" : ISODate("2017-11-28T13:28:44.455Z"),
            "status" : "N",
            "comment_text" : "fsdfdsf",
            "username" : "T"
        }, 
        {
            "created_date" : ISODate("2017-11-28T13:29:22.132Z"),
            "status" : "N",
            "comment_text" : "fdsfsdf",
            "username" : "dasdas"
        }, 
        {
            "created_date" : ISODate("2017-11-28T13:29:46.247Z"),
            "status" : "N",
            "comment_text" : "fdgdfgfd",
            "username" : "Vishnu T"
        }
    ]
}

我尝试了一些已经在堆栈流中的查询,例如

 mongo.filemanager.update(
            { "_id": req.body.id, "comments.comment_text": req.body.comments },
            { "$set": { "comments.$.status": 'Y' } }
        )

但是状态值没有改变。我在这里使用 Mongoose 。

请帮助我解决这个问题..提前致谢

已更新

mongo.filemanager.findOneAndUpdate(
        { "_id": req.body.id, "comments.comment_text": req.body.comments },
        {
           "$set": { "comments.$.status": 'Y' } 
        },
        function(err,doc) {
                if (err) throw err
                console.log("Updated Commentstatus")
        }
    );

最佳答案

这是 mongoose 中 update 的语法。

Model.update(条件、更新、选项、回调);

所以,

$set 应该是第二个参数,

尝试

mongo.filemanager.update({ "_id": req.body.id, "comments.comment_text": req.body.comments  },{ "$set": { "comments.status": 'Y' } })

Mongoose official Documentation

您还可以使用findOneAndUpdate

mongo.filemanager.findOneAndUpdate(
    { "_id": req.body.id, "comments.comment_text": req.body.comments },
    {
       "$set": { "comments.status": 'Y' } 
    },
    function(err,doc) {

    }
);

关于node.js - 如何在 Mongoose 查询对象中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47571226/

相关文章:

mongodb - 如何执行查找仅获取第一个元素

node.js - 如何让 Express 返回我刚刚在 MongoDB 中删除的对象

javascript - 未处理的PromiseRejection警告: TypeError: Cannot read property 'close' of undefined

node.js - 当条件时 Joi 循环依赖错误

javascript - 如何在mysql Node js中创建表?

windows - 在 Windows 7 和 Ubuntu 上使用相同的 mongodb 数据库

mongodb - 如何在 Mongoose 文档中允许自由格式的 JSON 数据?

mongodb - 如何使用 Mongoose 执行 runCommand?

node.js - 当嵌套数组为空时,$lookup 和 $unwind 不会给出结果

Node.js 数据库按顺序查询