【问题标题】:HOWTO: Produce mongoDB query string for the fields dynamically from a javascript app如何:从 javascript 应用程序动态生成字段的 mongoDB 查询字符串
【发布时间】:2013-06-23 19:09:06
【问题描述】:

我有一个带有 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)

如何为我想要检索的 SPECIFIC 字段动态生成字符串?

【问题讨论】:

  • 您不能在 JavaScript 中的快捷方式对象/属性创建语法中构建这样的字符串。您需要提前构造字符串:var profileFieldName='profile.'+field_name;
  • 这也行不通@WiredPrairie - 请参阅 Tad 的回答以了解需要如何完成。如果您为键名输入变量名 X,它将假定您想要名为 X 的键。
  • @AsyaKamsky - 当然......,JS有几处问题。
  • yup.... JS 确实有一些烦人的行为

标签: javascript node.js mongodb field


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2014-12-18
    相关资源
    最近更新 更多