如何:从JavaScript应用程序动态生成mongoDB字段查询字符串

3

我有一个使用MongoDB的Node.js应用程序
我的客户集合模式如下:

{
    '_id' : 1234341264876876143 , 
    'profile':{
        'name':  'bob',
        'email': 'bob@example.com',
        'DOB':   '13th April 1976'
    }
}

我想从我的Node应用程序中找到特定客户的profile.email字段,仅限此字段。
var field_name = "email";   // field_name selected programmatically from an array
db.collection('customers').find(
    {'_id':8965698756579084} , 
    {'profile.' + field_name :true}    // expecting it to become 'profile.email' 
)

但是,它会出现以下错误:
    {'profile.' + field_name :true}
                ^
SyntaxError: Unexpected token +
    at Module._compile (module.js:437:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)

我该如何动态生成字符串以检索我想要获取的具体字段?

在 JavaScript 中,您无法使用快捷对象/属性创建语法构建这样的字符串。您需要提前构建字符串:var profileFieldName='profile.'+field_name; - WiredPrairie
1
那也行不通,@WiredPrairie - 请参考Tad的答案了解如何完成。如果您将变量名X放入键名中,它将假定您想要名为X的键。 - Asya Kamsky
1
@AsyaKamsky - 当然..., JS 有几个问题。 - WiredPrairie
是的.... JavaScript确实有一些令人讨厌的行为 - Rakib
1个回答

4

将投影组件作为单独的步骤构建:

var projection = {};
projection['profile.' + field_name] = true;
db.collection('customers').find( {'_id':8965698756579084}, projection );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接