Reputation: 1042
I have a dataset in a mongo database with elements like this:
{
"fullname" : "Anonymous User",
"date" : ISODate("2016-12-09T04:00:27Z")
}
I am trying to search on the date and fullname terms.
In mongo (on the command line) if I do the following command I get a number of elements returned:
db.collection_name.find({ $and: [ { fullname: { $regex: "^Anonymous User$", $options: 'i' } }, {"date" : {"$lt" : ISODate("2016-12-19T00:00:00Z")}} ] }).pretty()
when the fullname matches and the date is less than the date given. This is great so I know my database has the data stored but the date and name are hard-coded.
I am writing a script in node.js and came up with this:
var fullname = "Anonymous User";
var today = new Date();
var search_term = { $and: [ { fullname: { $regex: "^" + fullname + "$", $options: 'i' } }, { date: { $lt: today } } ] };
I am trying to use the mongodb module and this snippet of code in my nodejs script:
db.collection( collection_name ).find( search_term ).toArray( function ( err, results ) { console.log(results); } );
But when I run my script no results are returned. There are no error messages - just that no items match and there are no results.
What am I doing wrong?
I think it may be something to do with how the date gets stored in the variable "search_term" but I don't know how to fix this. For example this works:
db.collection( collection_name ).find( { $and: [ { fullname: { $regex: "^Anonymous User$", $options: 'i' } }, { date: { $lt: new Date() } } ] } );
This doesn't work:
db.collection( collection_name ).find( search_term ).toArray( function ( err, results ) { console.log(results); } );
The only difference being I have replaced the find statement with "search_term".
I want to use the latter to avoid code duplication.
Upvotes: 0
Views: 1428
Reputation: 1043
You need to pass it like this
var today = new Date().toISOString()
Upvotes: 0