2016-03-04 95 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