How to check if collection exists in MongoDB with Node.js? [duplicate] How to check if collection exists in MongoDB with Node.js? [duplicate] mongoose mongoose

How to check if collection exists in MongoDB with Node.js? [duplicate]


If you want to hit mongodb directly via the node.js native api you can use db.collectionNames():

List existing collections

List names

Collections can be listed with collectionNames

db.collectionNames(callback);

callback gets two parameters - an error object (if error occured) and an array of collection names as strings.

Collection names also include database name, so a collection named posts in a database blog will be listed as blog.posts.

Additionally there’s system collections which should not be altered without knowing exactly what you are doing, these sollections can be identified with system prefix. For example posts.system.indexes.

Example:

var MongoClient = require('mongodb').MongoClient   , format = require('util').format;MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {  if(err) throw err;     db.collectionNames(function(err, collections){       console.log(collections);     }); });

http://mongodb.github.io/node-mongodb-native/markdown-docs/collections.html


You could use

 db.system.namespaces.find( { name: dbName +'.' + collectionName } );

It contains entries for collections and indices, for existing collection it should return something like this:

{ "name" : "temp333.categories" }

To do it from mongoose you could define system.namespaces model and query.