Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + Mongo native – check if collection exists before query

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.

like image 202
f1nn Avatar asked Dec 11 '22 20:12

f1nn


2 Answers

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" }
like image 50
j. andrew shusta Avatar answered Dec 29 '22 00:12

j. andrew shusta


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.

like image 20
snez Avatar answered Dec 29 '22 00:12

snez