Kar*_*hik 3 mongoose mongodb node.js pug
我正在查询我的 MongoDB,我想用 2 个表填充 UI:
我能够获取所有记录,但下面的当前记录查询不起作用。
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
});
});
Run Code Online (Sandbox Code Playgroud)
我正在做,{ _id: { $gt : myDate }}但它没有返回任何东西。
我究竟做错了什么?
从这篇Popping Timestamps into ObjectIds 文章中,您需要先将时间戳中的秒数转换为十六进制字符串,如下所示:
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 });
});
});
});
Run Code Online (Sandbox Code Playgroud)