1
db.collection('database_name')
  .find( { 'active':true, 'iOS':true} )
  .toArray (err, dbDocs) ->

returns me a result set .

However,

deviceName = 'iOS'
db.collection('database_name')
  .find( { 'active':true, deviceName:true} )
  .toArray (err, dbDocs) ->

doesnt work.

deviceName is a coffeescript string variable initialized to iOS deviceName = 'iOS'

How do I pass the variable deviceName?

1 Answer 1

3

You cannot use object literals if your field names are dynamic, you have to build the query object programmatically:

query = { active: true };
query[deviceName] = true if something;

db.collection('database_name').find( query ).toArray (err, dbDocs) ->
Sign up to request clarification or add additional context in comments.

3 Comments

{ $and: [ { 'active':true }, {'platform': { $in : ['Android'] } } ] } If I have to build a query like above, and ['Android'] is a dynamic variable. How to go about it ?
That's okay. Only dynamic field names are "tricky", for values you can use variables. { platform: { $in : anArrayVariable }}
db.collection('database_name').find( {$and: [ { active:true }, { platform: { $in : deviceName } } ] }).toArray (err, dbDocs) deviceName is an array for me and it will be populated at runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.