简体   繁体   中英

How to create a query on a Date field in MongoDB using mongoose?

I am trying to query a collection in Mongo database, to get all record with Time field in a date range. Time is defined as Date in database.
My environment: Node.js, Express, Jade, javascript.

This is the javascript code:

var query = {};
var timeQuery = {};
timeQuery["$lt"] = new Date().toISOString();
query["Time"] = timeQuery;
console.log(query);
db.model('testruns').find(query).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

the result printed to console:

{ Time: { '$lt': '2014-10-30T15:04:39.256Z' } }
0

The query returns 0 results (there should be more)

By the way... Running date queries from RoboMongo returns results, just the wrong ones. for example:

db.testruns.find({Time : {"$gte" : new Date("2014-10-30T15:13:37.199Z")}})

returns all records.

What I tried: This one , that one , another one , mongoose documentation of course, and many more results from google.

Most of them give the same answer, none of them works for me. HELP!

as far I see you are not including the field to reference in the query, can you try this: I assume your field name is 'time'

var date = new Date(); //or the date you want to compare
db.model('testruns').find({"Time":{"$lt":date}}).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

The problem was related to a schema definition, not directly to this code. The code of the query was correct. a schema definition had this field(Time) as String, which caused MongoDB to try and find a string in a date field...

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