How can I get all mongoDB collection names using Node.js code? - node.js

I want to store all collection names of MongoDB in a variable/array. How can I write nodeJS code to do that?

create a connection by providing connection url.
create a client to db using database name client.db(dbName);
call listCollections method to get detail info of each collection.
finally filter and push the required information and close the connection.
const mongo = require('mongodb').MongoClient;
mongo.connect(connectionUrl, function(err, client) {
let allCollections = [];
//create client by providing database name
const db = client.db(dbName);
db.listCollections().toArray(function(err, collections) {
if(err) console.log(err);
//iterate to each collection detail and push just name in array
collections.forEach(eachCollectionDetails => {
allCollections.push(eachCollectionDetails.name);
});
//close client
client.close();
});
});

await db.listCollections().toArray().map(c => c.name);
This returns a string array containing the name of every collection.

Related

Unable to extract collection names from mongodb

I have a mongodb (simple_demo) with an employee collection inside.
I am trying to connect to node JS and list the collections inside the simple_demo db.
I tried doing this but nothing came back. it just shows [].
Am wondering if I did anything wrong?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/simple_demo');
var db = mongoose.connection;
db.on('open', function () {
console.log("connection ok");
db.db.listCollections().toArray(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});
});
Good day
Your code works. Check your database.

Node Express Mongodb connection syntax and error handling

I was having an issue in my app that was simply from an oversight on the database name that I provided to my mongodb connection. While looking around I ran across the examples here:
https://wesleytsai.io/2015/08/02/mongodb-connection-pooling-in-nodejs/
So my question is why don't I get any kind of error thrown if I am providing a database that does not exist to the mongodb connection? I just need help interpreting/understanding the syntax below. On this line:
MongoClient.connect(mongoUrl, function(err, database) {
if( err ) throw err;
.
.
.
shouldn't an error be thrown since mongo can't connect if the database doesn't exist?
What I'm trying to do is setup some kind of error handling that can flag the fact the the database doesn't exist and likewise with the collection if that too does not exist ('expenses' should be 'test').
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var mongoUrl = 'mongodb://127.0.0.1:27017/expenses';
var db;
exports.connect = function(callback) {
MongoClient.connect(mongoUrl, function(err, database) {
if( err ) throw err;
db = database;
callback();
})
}
In mongodb, if you are connected to the datbase and then you provide a schema to a collection that you defined, then irrespective of the fact that whether that collection is there or not, mongodb creates a collection for you.
For example if you have the following code,
module.exports = mongoose.model('User', schema);
a collection named users is created in the database. So even if you dont have a collection, mongodb will create one for you.
If you want to check whether a database exists then follow like below:
var mongoose = require('mongoose')
, Admin = mongoose.mongo.Admin;
/// create a connection to ypur database
var connection = mongoose.createConnection(
'mongodb://user:password#localhost:port/your_database');
connection.on('open', function() {
// connection successful
new Admin(connection.db).listDatabases(function(err, result) {
console.log('listDatabases successful');
// the database lists are stored in result.databases
var allDatabases = result.databases;
// allDatabases contains the record of all the databases
// crosscheck this list with the database you want
});
});

Why is this query working in the mongo shell but not the node mongo driver?

I'm successfully running this query in the shell:
db.hourlydatas.find({'timeseries':ObjectId('1234')})
Trying to translate it to the mongo driver:
MongoClient.connect(config.db, function(err, db) {
// Use the admin database for the operation
var collection = db.collection('hourlydatas');
collection.find({'timeseries':'1234'}).toArray(function(err, docs) {
// assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
// callback(docs);
});
});
This does not return any documents, I assume because I'm not converting the string to an objectID. Is this possible in the driver?
Try this
var ObjectId = require('mongodb').ObjectID;
var collection = db.collection('hourlydatas');
collection.find({'timeseries':ObjectId('1234')}).toArray(function(err,docs) {...}
It should work, are you sure you are connecting to the same DB? check if both connections are to test or prod... I once wasted a lot of time on this just to find at the end that my mongo-shell was connected to prod while node was connecting to test.

how to create the collection in mongodb without any document using mongoose in nodejs

I have tried to copy collections from first db to second db, collections those having documents are copied from first db to second db, but collections with no documents are not getting copied. when I tried to create new collection with empty document, collection gets created with one document containing id field.But my requirement is to create collection without any document in mongodb using mongoose.How to create empty collection in MongoDb using mongoose library and node.js. here goes the code
var data = db.model('name', 'mymodel',"collectionName"),
newCollection = new data({});
newCollection .save(function (err) {});
You can use the native MongoDb driver to create an empty collection.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {
db.createCollection(collectionName, function(err, collection) {
db.close();
})
})
Now you can take this a step further and check if the collection exists. If its does skip creation or else create one.
MongoClient.connect('mongodb://localhost:27017/dbName', function(err, db) {
db.listCollections().toArray(function(err, collections) {
var collectionExists = false;
console.log(JSON.stringify(err,null,1));
if(!err && collections && collections.length>0){
_.each(collections,function (co) {
console.log(JSON.stringify(co.name,null,1));
if(co.name == collectionName){
collectionExists = true;
}
})
}
if(!collectionExists){
db.createCollection(collectionName, function(err, collection) {
})
}
db.close();
});
})
References:
http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection

Telling Mongoose which database to use - in a node.js Express application

I have an Node.js Express web app running.
I have two database connections, the system_db is created with "Mongoose.connect", the user_db is created with "Mongoose.createConnection". This seems to make them separate and have different connection pools. Although this could be the crux of the problem.
I have code dealing with with a Mongoose model
in the model file I have:
var authSchema = mongoose.Schema({
teamName: String,
league: String,
players: []
});
var Team = module.exports = mongoose.model('teams',authSchema);
in my main file I have two connections:
one is a system database
connection_uri = "mongodb://localhost:27017/";
system_db = mongoose.connect(connection_uri.concat("sparks"), {
native_parser : true
}, function(err){
if (err) throw err;
});
the other is a user database
user_db = mongoose.createConnection(connection_uri.concat(user_id));
then I have this piece of code in my main file which finds a Team object based off id:
app.param('team_id', function(req, res, next, team_id) {
Team.findOne(team_id, function(err, team) {
if (err) {
return next(err);
}
if (!team) {
throw new Error("no team matched");
}
req.team = team;
next();
});
});
the problem is that the app.param function above is not finding any matches for teams, even though they exist in a collection in the user_db database. this means, that I am thinking my model is pointing to the wrong database somehow? Somehow it must be pointing to this system_db instead of the user_db. Could this be right? How would I fix that?
The below method opens a connection to the system_db and is binded to the mongoose object,.i.e the current mongoose object is modified. The return type is not a Connection.
system_db = mongoose.connect(connection_uri.concat("sparks")...
Now when you again do:
user_db = mongoose.createConnection(connection_uri.concat(user_id));
This creates a new Connection to the user database and returns a connection, but does not modify the mongoose instance. The mongoose instance is still binded to the system_db database connection.
Since Team model is obtained from the same mongoose instance,
var Team = mongoose.model('teams',authSchema);
whatever operation is done on this model effectively occurs in the connection that the mongoose instance holds, and that is of the system_db database.
So you need to obtain the model from the user_db connection :
var user_db = mongoose.createConnection(..);
// retrieve the Team model
var Team= user_db.model('teams'); // not from mongoose instance.
use createConnection wherever you want to obtain a connection.

Resources