node.jsmongodbmongojs

How to check the collection is exist using MongoJS and Node.js


I need to check if the collection is exist in the DB using Node.js and MongoDB. Here I am using mongoJS as node driver. My code is below:

var mongoJs=require('mongojs');
var md5 = require('md5');
var dateTime = require('node-datetime');
var collections=['f_users'];
var MONGOLAB_URI="mongodb://user:*****123%40@ds127153.mlab.com:27153/fgdp";
var db=mongoJs(MONGOLAB_URI,collections);
exports.userSignup=function(req,res){
    var email=req.body.email;
    var password=req.body.password;
    var dob=req.body.dob;
    var dt = dateTime.create();
    var createdDate=dt.format('Y-m-d H:M:S');
    var updateDate=dt.format('Y-m-d H:M:S');
    db.f_user_login
    db.f_user_login.insert()
}

Here I need if collection f_user_login exist inside db or not. If not exist it will insert the required document.


Solution

  • I suppose that you first need to add the collection to your db.

    var db=mongoJs(MONGOLAB_URI,['f_user_login', 'f_users']);

    And then you can try running this

    var fUserLoginExist = db.f_user_login.findOne();
    if (fUserLoginExist) {
      // the collection exists
    } else {
      // the collection does not exist
    }
    

    Hope it helps