2013-10-02 78 views
0

业务架构的阵列通过的ObjectId搜索:更新的对象

var BusinessSchema = new Schema({ 
    owners: {type: Array}, 
    templates:[{ 
     _id : ObjectId, 
     title : String, 
     path : String, 
     custom_navigation : Boolean 
    }] 
}); 

业务集合看起来是这样的:

{"owners" : [ 
     ObjectId("522fa2d61685d3f4ce000002") 
    ], 
    "templates" : [ 
     { 
      "_id" : ObjectId("524c3bacc7ba62c549000004"), 
      "custom_navigation" : true 
     }, 
     { 
      "_id" : ObjectId("524c3bacc7ba62c549000005") 
     }, 
     { 
      "_id" : ObjectId("524c3bacc7ba62c549000006") 
     } 
    ]} 

功能更新存储在模板阵列特定模板:

 var Business = require('../models/business.js'); 

     Business.update({'owners' : req.user._id, "templates._id" : req.body._id}, { 
      $set : {"templates.$.custom_navigation" : req.body.custom_navigation} 
     }, 
     function(err, numUpdated){ 
      console.log(numUpdated); 
      if(numUpdated > 0){ 
       res.json(200, req.body); 
      }else{ 
       res.json(404); 
      } 
     }); 

当我输出update函数的搜索参数时,我看到这个:

{ owners: 522fa2d61685d3f4ce000002, 
    'templates._id': '524c3bacc7ba62c549000004' } 

。注意,猫鼬似乎认识到req.user._id为的ObjectId,但req.body._id作为字符串传递。我试图将其转换为ObjectId而没有结果。无论template._id设置为什么,update语句都会更新模板数组中的第一项。

回答

0

您需要通过对象ID搜索并仅仅不req.body._id(我猜测它是一个整数)

var templateId = require('mongoose').Types.ObjectId; 
Business.update({'owners' : req.user._id, "templates" : {$elemMatch :{ _id: new templateId(req.body._id)}}},  
.... 
+0

“我试图将其转换没有结果OBJECTID。” –

+0

我忘了模板是一个数组..我已经修改了答案,请试试看.. – Sriharsha

+0

@KingJulian你可以试试更新后的代码吗? – Sriharsha