Reputation: 7568
I am working on a mongoose query that deals with nested data.
Example of data:
{
name : 'blah',
en : {
state : 'published',
pubDate : '2015-10-19-22T13:44:16.387Z'
},
es : {
...
},
...
}
I want to query the date for all objects with a publication date (pubDate
) earlier than today or blank. My Schema has the pubDate
nested by language (en
, es
, etc.)
My application has a locals
object that stores some useful values: for this purpose I have locals.today
which maps to today's date as well as locals.lang
which maps to the users' currently selected language.
Using mongoose I can query for an individual parameter using where:
.where(locals.lang + '.pubDate').lt(locals.today)
What I can't seem to accomplish is to use the or query operator as it doesn't recognize the locals object inside of it.
.or([
{ locals.lang + '.pubDate' : { '$lt' : locals.today } },
{ locals.lang + '.pubDate' : '' }
])
I can confirm that this syntax works if I hardcode the language portion ('en.pubDate'
instead of locals.lang + '.pubDate'
) but this is not a viable solution in my application. Also I have tried setting up a new variable (var publicationdate = locals.lang + '.pubDate'
) but that does not work either. It seems the syntax does not like having a variable for the property name.
Does anyone know how I can use the variables within the or
query syntax in mongoose?
Thanks
Upvotes: 0
Views: 288
Reputation: 103305
Using the bracket notation
to create object properties on the fly, you can set up the query objects as follows:
var firstObj = {},
secondObj = {};
firstObj[locals.lang + '.pubDate'] = { '$lt' : locals.today };
secondObj[locals.lang + '.pubDate'] = '';
which you can then use as:
.or([ firstObj, secondObj ])
Upvotes: 2