I have a Node.js app with MongoDB
My customers collection schema is like this:
{
'_id' : 1234341264876876143 ,
'profile':{
'name': 'bob',
'email': 'bob@example.com',
'DOB': '13th April 1976'
}
}
I want to find ONLY the profile.email
field of a particular customer from my Node app
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'
)
But, it gives the following error:
{'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)
How do i produce the string dynamically for the SPECIFIC fields that i wanna retrieve?
Construct the projection component as a separate step:
var projection = {};
projection['profile.' + field_name] = true;
db.collection('customers').find( {'_id':8965698756579084}, projection );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.