问题
I am querying my MongoDB and I want to populate UI with 2 tables:
- all records from db
- current records, created within last hr
I am able to get all records, but the current record query below is not working.
app.get('/', function(req, res) {
var myDate = new Date(Date.now() - 1 * 60 * 60 * 1000);
var curr = MyCollection.find(
{_id: { $gt : myDate }}
).exec();
MyCollection.find({}, function(err, doc) {
res.render('index.jade', {latest: curr, all: doc}); //this query
});
});
I am doing { _id: { $gt : myDate }}
but it does not return anything.
What am I doing wrong?
回答1:
From this post Popping Timestamps into ObjectIds, you need to convert the seconds from the timestamp to hexidecimal string first, something like the following:
var ObjectID = require('mongodb').ObjectID;
app.get('/', function(req, res) {
var timestamp = new Date(Date.now() - 1 * 60 * 60 * 1000);
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = ObjectID(hexSeconds + "0000000000000000");
console.log(constructedObjectId); // prints 564cd3810000000000000000
MyCollection.find({}, function(err, doc) {
MyCollection.find({
"_id": { "$gt" : constructedObjectId }
}, function (err, curr) {
res.render('index.jade', { "latest": curr, "all": doc });
});
});
});
来源:https://stackoverflow.com/questions/33788353/nodejs-and-mongoose-find-records-from-last-hour