【问题标题】:MongoDB and MongoJS - can't get runCommand to work for text queriesMongoDB 和 MongoJS - 无法让 runCommand 用于文本查询
【发布时间】:2013-08-27 00:43:29
【问题描述】:

我的目标是使用来自 Node.js 的 MongoDB (2.4.4) 文本命令。它可以从命令行正常工作。基于这个先前的 SO 问题:Equivalent to mongo shell db.collection.runCommand() in Node.js,我尝试使用 MongoJS (0.7.17) 但无法成功。代码如下:

mongojs = require('mongojs');
var products = mongojs('localhost:27017/mydb').collection('products');
products.runCommand('text', {search: 'a'}, function (err, docs) {
   ...
});

docs 返回 undefined 并且 err 为空。我可以很好地执行 products.find() 之类的普通函数...并且可以在 MongoDB 命令行上执行搜索。有谁知道怎么做?

顺便说一句,这是回调中文档包含的内容:

{
    "queryDebugString": "||||||",
    "language": "english",
    "results": [],
    "stats": {
        "nscanned": 0,
        "nscannedObjects": 0,
        "n": 0,
        "nfound": 0,
        "timeMicros": 55
    },
    "ok": 1
}

顺便说一句,如果有另一种方法可以仅使用普通的本机驱动程序使其工作,那我很好。

【问题讨论】:

    标签: node.js mongodb mongojs


    【解决方案1】:

    使用本机驱动程序,我可以从 db 对象运行命令,如下所示:

    var MongoClient = require("mongodb").MongoClient;
    MongoClient.connect(database, function (err, db) {
        if (!err) {
            db.command({ distinct: "Messages", key: "session" }, function (err, result) {
                //more code here
            });
        }
    });
    

    我注意到您正在从集合对象运行命令,这可能是问题所在。

    【讨论】:

    • 是的,虽然 mongojs 文档说应该可以。我刚刚得到了你建议的一个变体......而不是运行数据库。谢谢。它看起来像:db.command({ text: 'products', search: 'mysearchterm' }, function(e, o) {});
    • 有人能解释一下使用 find 和使用 db.command 的区别吗?为什么我不能将文本索引与 find 一起使用。这不是更好地遵循惯例吗?
    • 我得到 db.command 不是一个函数,我有 mongodb 3.0.6 并且使用 runCommand 也得到了相同的结果
    • @NaguibIhab 那是因为您没有在 url 中包含数据库名称。例如:如果您使用数据库 url 以 host:port 连接它会给出错误,所以正确的方法是使用 url 作为 host:port/dbName 或使用变量 let DB = db.db(dbName); DB.command({})
    【解决方案2】:

    你需要在 db 对象中调用命令,而不是在 connect 对象中

    MongoClient.connect(url, function (err, db) {
        if (!err) {
            var dbo = db.db();
            dbo.command({ insert: "mycollection", documents: [{"test":1}]}, function 
    (err, result) {
    
                if (err)
                {
                    console.log(err);
                }else
                {
                    console.log("1 document inserted",result);
                }
                }
            );
    
            }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多