如何在mongoose中更新数组

时间:2016-10-24 09:12:26

标签: node.js mongodb mongoose

我有一个突出显示的架构:

var newshighlightSchema = new mongoose.Schema({
    volumeNo:String,
    week:String,
    status:String,
    adminApp : Boolean,
    reviewerApp:Boolean,
    ttheadApp:Boolean,
    comment:String,

    highlight:[{
            createdby:String,
            level : String,
            title : String,
            description: String        
            }]
});

db:

中已存在以下数据
{
        "_id" : ObjectId("580daa749c6e2e1830a54fe5"),
        "volumeNo" : "100",
        "week" : "W44Y2016",
        "status" : "false",
        "adminApp" : false,
        "reviewerApp" : false,
        "ttheadApp" : false,
        "comment" : "",
        "highlight" : [
                {
                        "createdby" : "58047db9f8995a147ce3fmeo",
                        "level" : "Accolades",
                        "title" : " the news title",
                        "description" : "Description of news title",
                        "_id" : ObjectId("580daa749c6e2e1830a54fe6")
                }
        ],
        "__v" : 0
}

我想更新title and description以上数据的object id =580daa749c6e2e1830a54fe6

我在模型中创建了一个静态函数:

newshighlightSchema.statics.updateLevel=function(savedata, callback){ 
        console.log("data is model updating ",savedata);

    this.update({'highlight._id':savedata._id},{'$set':{
        'highlight.title':savedata.title,
        'highlight.description':savedata.description
    }},function(err){
        callback(err,null);
        console.log("Err in updating",err);
    })
}

以上功能中的savedata是:

savedata = { createdby: '58047db9f8995a147ce3fmeo',
  timestamp: 'Monday, 24th October 2016',
  testlabel: 'qq',
  level: 'Accolades',
  title: 'Updated news title',
  description: 'updated Description',
  _id: '580daa749c6e2e1830a54fe6',
   }

这在mongoose中不起作用。任何的想法? **请注意我想用猫鼬做这个。不在mongodb客户端。 **

1 个答案:

答案 0 :(得分:0)

使用$,

 this.update({'highlight._id':savedata._id},{'$set':{
       'highlight.$.title':savedata.title,
        'highlight.$.description':savedata.description
  }},function(err){

cf:Update nested mongo array