NodeJS + Mongo native – check if collection exists before query

collections, mongodb, node.js

Solution

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);
        });
    });
};

Problem

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.

Original source