Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS中的MongoDB ObjectID_Javascript_Node.js_Mongodb_Mongojs - Fatal编程技术网

Javascript JS中的MongoDB ObjectID

Javascript JS中的MongoDB ObjectID,javascript,node.js,mongodb,mongojs,Javascript,Node.js,Mongodb,Mongojs,我正在尝试使用MongoDB进行分页,而不使用skip() 在MongoShell中,我通过查询得到了以下结果,但在Javascript中是空的[] 我认为我的ObjectID做得不对,我在Node.js中使用了“mongodb ObjectID”和“mongojs”libs Mongo shell: db.chat.find({ _id: { $lt: ObjectId("53e901c125c68270311e5f41") }, user_id: 1, target_user_i

我正在尝试使用MongoDB进行分页,而不使用skip()

在MongoShell中,我通过查询得到了以下结果,但在Javascript中是空的[]

我认为我的ObjectID做得不对,我在Node.js中使用了“mongodb ObjectID”和“mongojs”libs

Mongo shell:

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);
{ "_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.
输出:

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);
{ "_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

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:[]"
  }
});
用JS查询如何得到相同的结果

使用文档中的$oid编辑

仍然不工作

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)
编辑 现在只需使用以下内容:

var last_ts = "53e901c125c68270311e5f41";
new ObjectID(last_ts)

如果我没有弄错,您只需将ObjectID字符串传递给mongo查询:

db.chat.find({
    _id: { $lt: last_ts},
    user_id: 1,
    target_user_id: 1,
    "$or": [{user_id: 1, target_user_id:1}]
})
...
不,你用的不是ubless。