【问题标题】:How to update an array in mongoose [duplicate]如何在猫鼬中更新数组[重复]
【发布时间】:2016-10-24 17:54:05
【问题描述】:

我有一个高亮模式:

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
}

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

我在模型中做了一个静态函数,如下所示:

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 = { createdby: '58047db9f8995a147ce3fmeo',
  timestamp: 'Monday, 24th October 2016',
  testlabel: 'qq',
  level: 'Accolades',
  title: 'Updated news title',
  description: 'updated Description',
  _id: '580daa749c6e2e1830a54fe6',
   }

这在猫鼬中不起作用。任何想法? **请注意,我想在猫鼬中执行此操作。不在mongodb客户端中。 **

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用 $,

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

    cf : Update nested mongo array

    【讨论】:

    • 之前我试过也放“$”也无济于事。它仍然没有更新。
    • 可能是 _id 字段有问题,尝试使用 ObjectId : const ObjectId = mongoose.Types.ObjectId; {'highlight._id': new ObjectId(savedata._id)},
    猜你喜欢
    • 2019-09-30
    • 2020-08-05
    • 2015-06-03
    • 2021-04-28
    • 2017-05-20
    • 2019-07-26
    • 2015-04-29
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多