Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a new database in MongoDB with Mongoose?

I am trying to figure out if I can create a new database in MongoDB with Mongoose. I am running on Node, and I know the MongoDB driver for Node can do it, but I am wondering if I can do it just from Mongoose.

Is there an equivalent to the db.createCollection(name, options) from the Node MongoDB driver in Mongoose? My google skills are failing right now.

I just was trying to figure out if I had to install the whole MongoDB driver just for that, but I think I do.

like image 632
ptf Avatar asked Jun 29 '15 21:06

ptf


People also ask

Can we create database in MongoDB?

Creating a MongoDB database with the CLIMongoDB only creates the database when you first store data in that database. This data could be a collection or a document. To add a document to your database, use the db. collection.

Does mongoose create a database if not exists?

Mongoose. Connect Doesn'T Create Database If Not Exist With Code Examples.

Can I use mongoose with MongoDB?

Mongoose is an ODM (Object Data Modeling) library for MongoDB. While you don't need to use an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool to have a great experience with MongoDB, some developers prefer them.


1 Answers

Yes, you can specify the database name in your connection string.

db = mongoose.connect('mongodb://localhost/dbname1')

As soon as you create a record with that connection, it will create the new database and collections under the database name of 'dbname1'. If you wanted to create a new database, you can specify a different connection string:

db = mongoose.connect('mongodb://localhost/dbname2')

and that will create all your records under the name 'dbname2'. Your documents will not import over to dbname2, you will have to do an import of those records if you wanted to do that. Hope that helps.

like image 129
Eric Hartmann Avatar answered Oct 26 '22 19:10

Eric Hartmann