NodeJS + Mongo native - 在查询之前检查集合是否存在

f1n*_*1nn 3 collections mongodb node.js

我有一个函数,试图从MongoDB中的设置集合中获取特定值.设置集合中包含设置值的设置对象标记为{'settings':'settings'}.架构是:

collection:setting
|--object
   |--{'settings':'settings'}
   |--{'valueA':'valueA'}
   |--...
Run Code Online (Sandbox Code Playgroud)

问题是当我第一次查询设置对象时,集合'settings'根本不存在.所以,

exports.getInstruments = function (callback) {
db.collection("settings", function(error, settings) {
    settings.find({ "settings" : "settings" }), (function(err, doc) {
           callback(doc.instruments);
    }); 
]);  
}
Run Code Online (Sandbox Code Playgroud)

只是挂起并且不调用回调.如果收集不存在,我应该返回""或未定义,否则 - doc.instrumens.

j. *_*sta 10

有一个exists()函数可用于确定是否执行挂起的代码.

> db.getCollection('hello').exists()
null
> db.getCollection('world').exists()
{ "name" : "testdb.world" }
Run Code Online (Sandbox Code Playgroud)

  • `let col = db.collection('foo'); console.log(col.exists())返回col.exists不是一个函数。这在mongodb本机驱动程序2.2.25中有效吗? (2认同)

Joh*_*yHK 2

您不需要专门处理新的集合案例,我认为问题出在您的代码上。

除了一些语法问题之外,主要问题是find将 a 传递Cursor给回调函数,而不是第一个匹配的文档。如果您只需要一份文档,findOne则应该使用。

这应该有效:

exports.getInstruments = function (callback) {
    db.collection("settings", function(error, settings) {
        settings.findOne({ "settings" : "settings" }, function(err, doc) {
            callback(doc && doc.instruments);
        });
    });
};
Run Code Online (Sandbox Code Playgroud)