如何使用mongoose更新mongodb中的元素数组

时间:2017-05-24 08:08:46

标签: node.js mongodb mongoose

我有这样的文档结构

 username : String,
    notification:{
       id:String,username:String,desc:String,created: Date,status:Boolean,flag:String
    },

示例数据

"notification" : [
                {
                        "status" : true,
                        "created" : ISODate("2017-05-24T06:41:55.735Z"),
                        "desc" : "kamu baru saja mendapatkan pesan dari GILANG",
                      
                        "username" : "GILANG",
                        "id" : "141ee270-404c-11e7-a6a0-fb6a792329ad"
                },

在Robomongo内部,我成功使用此查询

db.getCollection('members').update( {'notification.id':'141ee270-404c-11e7-a6a0-fb6a792329ad'},
        { $set:{'notification.$.status':false} }

然后我使用mongoose查询无法正常工作

 member.update({'notification.id':id},
    {'$set':
        {
          'notification.$.status':false

        }
    }, (err,data) => {
      if(err) {
        console.log(err);
         callback({"message":err,"status":"error","statuscode":"400"})
      } else {
        console.log(`success delete notification${id}`);
          callback({"message":data,"status":"success","statuscode":"200"});
      }

    });

在我的package.json中就像这样

"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"ejs": "~2.5.6",
"express": "~4.15.2",
"mongoose": "^4.9.9",

1 个答案:

答案 0 :(得分:0)

我认为问题出在您的架构中。尝试将通知模式定义从对象更改为数组:

notification:[{
       id:String,username:String,desc:String,created: Date,status:Boolean,flag:String
    }],