简体   繁体   English

使用NodeJS,MongoDB和Monk更新数组项

[英]Updating an array item using NodeJS, MongoDB & Monk

I have a data set like this: 我有这样的数据集:

{ 
  name : 'Doc Name',
  photos: [
      {
        name: 'photo1',
        url: 'http://.....'
      },
      {
        name: 'photo2',
        url: 'http://......'
      }
   ],
   etc ...

Using Monk https://github.com/LearnBoost/monk how do I update photo2? 使用Monk https://github.com/LearnBoost/monk如何更新photo2? I can use an index as I am iterating over the fields at the moment. 我可以使用索引,因为我正在迭代字段。

My current attempt below gives me an error, and I can't use a variable for the JSON selector (as in the index). 我下面的当前尝试给了我一个错误,我不能为JSON选择器使用变量(如在索引中)。

collection.update({_id: data._id}, {photos[i].data: filename}, function(err, updatedata) {

            });

Updating items at a position in an array can be done using the positional $ operator 可以使用位置$运算符更新数组中某个位置的项目

collection.update( 
    { _id: data.id, "photos.name": "photo2" }, 
    { $set: { "photos.$.data": "yourdata" } }
)

So I found a solution to my problem but there may be some better options and I will leave it unanswered. 所以我找到了解决问题的方法,但可能会有一些更好的选择,我将不予回答。 But for anyone else with the same issue this is what I did: 但对于有同样问题的其他人来说,这就是我所做的:

I extracted the MongoDB document as an object in Node.js, manipulated the document, and then replaced the entire array in a single update statement. 我将MongoDB文档作为Node.js中的对象提取,操作文档,然后在单个更新语句中替换整个数组。 For example here is some pseudo code: 例如,这里有一些伪代码:

collection.find({id: 1}, function(err, doc){
    for(i=0; i< doc.array.length; i++) {
          //do what you gotta do
          doc.array[i].property = 'new value';
    }
    collection.update({id: 1}, {$set : {"doc.array": doc.array}}, function(err,doc){
          console.log(err);
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM