NodeJS + Mongo native – check if collection exists before query

↘锁芯ラ 提交于 2019-12-14 01:41:39

问题


I've got a function, trying to get a specific value from settings collection in MongoDB. The marker for settings object, containing settings values, in settings collection is {'settings':'settings'}. The schema is:

collection:setting
|--object
   |--{'settings':'settings'}
   |--{'valueA':'valueA'}
   |--...

The problem is when I first time query settings object, the collection 'settings' simply does not exists. So,

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

just hangs and callback is not invoked. If collection does not exist, I should return "" or undefined, else - doc.instrumens.


回答1:


You shouldn't need to specially handle the new collection case, I think the problem is with your code.

Aside from some syntax problems, the main problem is that find passes a Cursor to your callback function, not the first matching document. If you're expecting just one doc, you should use findOne instead.

This should work:

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



回答2:


There's an exists() function that you could use to determine whether or not to execute the code that hangs.

> db.getCollection('hello').exists()
null
> db.getCollection('world').exists()
{ "name" : "testdb.world" }



回答3:


You could potentially take advantage of db.createCollection which explicitly creates a collection:

> db.createCollection("asd")
{ "ok" : 1 }
> db.createCollection("asd")
{ "errmsg" : "collection already exists", "ok" : 0 }

Just check if the command succeeded based on the ok field.



来源:https://stackoverflow.com/questions/13395041/nodejs-mongo-native-check-if-collection-exists-before-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!