2013-10-02 123 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