2015-09-15 230 views
0

查詢的用戶變量,看起來像這樣:查詢與貓鼬

var getUser = function(query) { 
    var q = query.q, by = query.by === 'id' ? '_id' : query.by; 
    Account.findOne({by:q}).exec(function(error, result) { 
    console.log('error: ' + error); 
    console.log('result: ' + result); 
    }); 
} 
getUser({by: 'id', q: '53mklmrt34klm'}); 

結果是:

error: null 

result: null 

有沒有辦法實現與無論是在數據和變量查詢字段名?

回答

2

您定義您的方式JSONquery param對於Account.findOne是不正確的。

相反的:

Account.findOne({by:q}).exec(function(error, result) {/* Your code here */}); 

用途:

var queryParam = {}; 
queryParam[by] = q; 
Account.findOne(queryParam).exec(function(error, result) {/* Your code here */}); 
+1

謝謝。後來我發現它已經在這裏回答:http://stackoverflow.com/questions/17039018/how-to-use-a-variable-as-a-field-name-in-mongodb-native-findone – Yaakov