Mongo:更新嵌套数组中的对象时出现遍历错误

时间:2015-02-20 05:02:05

标签: node.js mongodb mongoose mongodb-query

我正在尝试在Mongoose的嵌套数组中的对象中将floor_num值从1更新为9000

thingSchema.findById(thingID, function(err, lm) {
  if (!lm){
    console.log(err);
  }
  else {
      lm.update({'style.maps.localMapArray.map_marker_viewID': req.body.map_marker_viewID}, 
      {'$set': {
        'style.maps.localMapArray.$.floor_num': 9000,
      }
      }, function(err) {
        //update success
    });
  }
}); 

但是我收到了这个Mongo错误:

MongoError: cannot use the part 
   (localMapArray of style.maps.localMapArray.map_marker_viewID) to traverse
   the element ({localMapArray: [ { map_marker_viewID: "acympqswmkui", 
   floor_num: 1 } ]} code: 16837

我的架构:

   var thingSchema = new Schema({
        style: {
            maps: {
                localMapArray: [{
                   map_marker_viewID : String,
                   floor_num : Number
                }],
            }
        }
   }); 

1 个答案:

答案 0 :(得分:2)

这是我解决此类问题的方法。我也是MongoDB和Mongoose的新手。

thingSchema.findById(thingID, function(err, lm) {
    if (err)
        console.log(err);

    var localMaps = lm.style.maps.localMapArray;

    for (var i = 0; i < localMaps.length; i++) {
        if (lm.style.maps.localMapArray[i].map_marker_viewId == req.body.map_marker_viewID) {
            lm.style.maps.localMapArray[i].floor_num = 9000;
        }
    }

    lm.save();
});

我希望这里的某个地方可以用Mongoose提供更好的例子。希望它会对你有所帮助。