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.
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" }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With