Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Basically, I want to hide a div based on whether a collection exists or not. Does anyone know the simplest way to do so? I am using Mongoose and Express.js with Jade.

like image 764
Ralph David Abernathy Avatar asked Oct 20 '22 08:10

Ralph David Abernathy


1 Answers

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

like image 134
John Petrone Avatar answered Oct 23 '22 03:10

John Petrone