将变量传递给nodejs中的mongodb查询

时间:2015-01-29 16:00:23

标签: node.js mongodb

我可以将变量传递给查询,所以:

db.collection('coll').find(query).toArray(function(err, docs) {
    if(err) throw err;
    docs.forEach(function(doc) {
        var Id = parseInt(doc._id); // a returnd _id from previous query
        Id--;
        query = {_id : parseInt(doc._id) }; // returns null
        // OR query = {_id : Id }; // error
        db.collection('coll').find(query).toArray(function(err, beforeDocs) {
            //if (err) throw err;
            console.dir(beforeDocs);
        });
});

实际上我要做的是通过id查询来获取第一个查询中给出的结果之前的记录

任何想法??

是否可以用变量查询mongodb ??

var query = { _id : var i, name : var name , etc...}

1 个答案:

答案 0 :(得分:0)

无法在mongodb查询中搜索匹配前显示的文档。

我相信你最好的选择是这样的:

var prevDoc = null;  // to store the previous document
var cursor = db.collection('collection').find({}); // get all docs
cursor.sort('_id', 1); // it only makes sense to grab previous if they're sorted
cursor.each(function(err, doc) {
  if(err) throw err;
  if(doc == null) { // if we reached the end of our cursor...
    db.close();     // close the db connection
  } else {
    if( doc.foo === "bar" ) { // here you put your match criteria
      console.dir(prevDoc); // here you print your previous document
    }
  }
  prevDoc = doc; // store current doc so that it's available for next iteration
});

要回答您的直接问题(“是否可以使用变量查询mongodb?”),可以使用包含在创建查询时已具有值的变量的查询来查询mongodb。但是,不可能为mongodb传递新的未实例化变量以便以某种方式进行操作。