2012-06-25 45 views
6

我沒有設置變量更新,我的代碼的關鍵...如何通過mongoose,Node.js中的var設置關鍵字?

mongoose.model('members', Schema).update({ id: '0' }, {$push: {'this_key': 'value'}} , [], function (err, data){}); 

如果我使用

var this_key = 'test'; 

但this_key不是 'this_key' 在 '測試' 是

mongoose.model('members', Schema).update({ id: '0' }, {$push: {this_key: 'value'}} , [], function (err, data){}); 

我需要得到一些價值EXT POST []設置變量this_key,

^h ow通過mongoose中的變量設置關鍵字,Node.js?

回答

13

對象字段名稱中的字符串文字的語法在這裏咬你。爲了避開它,創建一箇中間對象,並在不使用文字的情況下構建它:

var this_key = 'test'; 
var push = {}; 
push[this_key] = 'value'; // here, it will use the variable 

mongoose.model('members', Schema).update(
    { id: '0' }, {$push: push} , [], function (err, data){}); 
+0

非常感謝。^_^ –

+0

幫助人們差不多6年後! – DORRITO