[英]MongoDB ObjectID in JS
I am trying to make pagination work with MongoDB without skip(); 我正在尝试在不使用skip()的情况下使用MongoDB进行分页;
In mongo shell I got the following results with my query, but in Javascript a empty []; 在mongo shell中,我的查询得到以下结果,但在Javascript中为空[];
I think I am doing the ObjectID wrong, I use the "mongodb ObjectID" and "mongojs" libs with Node.js. 我想我做错了ObjectID,我在Node.js中使用了“ mongodb ObjectID”和“ mongojs”库。
Mongo shell: Mongo外壳:
db.chat.find({
_id: { $lt: ObjectId("53e901c125c68270311e5f41") },
user_id: 1,
target_user_id: 1,
"$or": [{user_id: 1, target_user_id:1}]
}).sort({
ts: -1
}).limit(5);
Output: 输出:
{ "_id" : ObjectId("53e88e1bb76e781413000029"), "user_id" : 1, "target_user_id" : 1, "message" : "Hey" }
{ "_id" : ObjectId("53e88f51b76e78141300002a"), "user_id" : 1, "target_user_id" : 1, "message" : "Hey" }
//ect.
Javascript Java脚本
var ObjectID = require('mongodb').ObjectID;
var db = require("mongojs").connect(db_uri, db_collections);
//last_ts = "53e901c125c68270311e5f41"
var last_id = ObjectID.createFromHexString(last_ts);
db.chat.find({
_id: { $lt: last_id },
user_id: 1,
target_user_id: 1,
"$or": [{user_id: 1, target_user_id:1}]
}).sort({
ts: -1
}).limit(5).toArray(function (err, docs) {
console.log("docs:"+docs); //"docs" - no result
console.log("err:"+err); //"err:null"
if(docs != null){
console.log(JSON.stringify(docs)); //"docs:[]"
}
});
How can I get the same result, with my query in JS? 我如何在JS中获得相同的结果?
Edit with $oid from the docs: 使用文档中的$ oid进行编辑 :
http://docs.mongodb.org/manual/reference/mongodb-extended-json/#oid http://docs.mongodb.org/manual/reference/mongodb-extended-json/#oid
Still not working.. 还是行不通..
var last_ts = "53e901c125c68270311e5f41";
db.chat.find({_id: {$lt: {"$oid": last_ts}}, user_id:1, target_user_id:1, "$or": [{user_id: 1, target_user_id:1}]}).sort({ts: -1}).limit(5)
Edit Now working with simply as: 立即编辑的使用方式如下:
var last_ts = "53e901c125c68270311e5f41";
new ObjectID(last_ts)
If I'm not mistaken, you can simply pass the ObjectID string to the mongo query: 如果我没记错的话,您可以简单地将ObjectID字符串传递给mongo查询:
db.chat.find({
_id: { $lt: last_ts},
user_id: 1,
target_user_id: 1,
"$or": [{user_id: 1, target_user_id:1}]
})
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.