【问题标题】:Why is this query working in the mongo shell but not the node mongo driver?为什么此查询在 mongo shell 中有效,但在节点 mongo 驱动程序中无效?
【发布时间】:2017-05-28 01:56:58
【问题描述】:

我在 shell 中成功运行了这个查询:

db.hourlydatas.find({'timeseries':ObjectId('1234')})

尝试将其翻译成 mongo 驱动程序:

MongoClient.connect(config.db, function(err, db) {
// Use the admin database for the operation

var collection = db.collection('hourlydatas');

collection.find({'timeseries':'1234'}).toArray(function(err, docs) {
//   assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
// callback(docs);
});      

});

这不会返回任何文档,我假设是因为我没有将字符串转换为 objectID。这在驱动程序中可能吗?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    试试这个

    var ObjectId = require('mongodb').ObjectID;
    var collection = db.collection('hourlydatas');
    collection.find({'timeseries':ObjectId('1234')}).toArray(function(err,docs) {...}
    

    【讨论】:

    • 它实际上不是一个整数,它和对象 ID 字符串。实际的 objectid 是一个长字符串,如 5019ijasWQa231,但为简单起见,我更改了它
    【解决方案2】:

    它应该可以工作,您确定要连接到同一个数据库吗?检查两个连接是要测试还是生产......我曾经在这上面浪费了很多时间,只是为了最后发现我的 mongo-shell 连接到生产,而节点正在连接到测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2016-11-15
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多