简体   繁体   中英

How do you match by date in mongodb using node js?

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.

你需要这样通过

var today = new Date().toISOString()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM