2016-03-04 48 views
1

創建密鑰這裏是我的架構:貓鼬:動態與Schema.Types.Mixed

var Account = new Schema({ 
    username: String, 
    likes: Schema.Types.Mixed 
}) 

在這裏,我將'someProperty'財產喜歡。一切正常。

var conditions = {'_id':req.body.id}; 
var update = {'$set':{'likes.someProperty': req.body.something}}; 
var callback = function (err, data) { 
    if (err) return next(err); 
}; 
users.update(conditions, update, callback); 

更新我的文檔後:

'username': Fat Gandalf, 
'likes': { 
      someProperty: '100' 
     } 

我的問題是,我不知道 'someProperty' 的名稱。我需要以某種方式動態創建它:

var temp = 'likes.' + req.body.propertyName; // -- > 'likes.anything' 
var update = {'$set':{temp: req.body.something}}; 

上述示例不起作用。他媽的!需要你的幫助!

回答

1

使用square bracket notation構造域對象如下:

var conditions = { "_id": req.body.id }, 
    update = { "$set": {} }; 

update["$set"]["likes."+req.body.propertyName] = req.body.something; 
Users.update(conditions, update, callback); 

或者使用computed property names (ES6)

var conditions = { "_id": req.body.id }, 
    update = { 
     "$set": { 
      ["likes."+req.body.propertyName]: req.body.something 
     } 
    }; 
Users.update(conditions, update, callback); 
+1

它的工作就像一個魅力!謝謝你,先生!我很感激你,有什麼方法可以幫助你解決問題嗎? –

+0

@EugeneEpifanov無後顧之憂,總是樂於幫助:) – chridam