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)

検索したいSPECIFICフィールドの文字列を動的に生成するにはどうすればよいですか?

4

1 に答える 1

4

投影コンポーネントを別のステップとして構築します。

var projection = {};
projection['profile.' + field_name] = true;
db.collection('customers').find( {'_id':8965698756579084}, projection );
于 2013-06-23T19:52:56.327 に答える