Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.connect doesn't create database if not exist

I'm new on NodeJs, I'm learning how to connect to mongodb using NodeJS with Mongoose library. As I know, when I connect to database with a name, if this database with that name doesn't exist, then mongoose will create it automatically, but it's not being created with me. Here is my code:

const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/mongo-test", {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));

mongoose version: ^5.2.5

like image 893
Khalid Taha Avatar asked Jul 25 '18 16:07

Khalid Taha


People also ask

Does MongoDB create database if not exists?

Creating a DatabaseMongoDB will create the database if it does not exist, and make a connection to it.

Does mongoose connect create a database?

The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model SomeModel above), and the second argument is the schema you want to use in creating the model.

Does mongoose create collection automatically?

Here mongoose will check if there is a collection called "Users" exists in MongoDB if it does not exist then it creates it. The reason being, mongoose appends 's' to the model name specified. In this case 'User' and ends up creating a new collection called 'Users'.

What is the difference between mongoose connect and mongoose createConnection?

My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used.


2 Answers

Pedro is right, when you save your first document in the database, mongoose will create the database and the collection for this document.

The name of the database will be the name specified in the connection, in this case myapp:

mongoose.connect('mongodb://localhost:27017/myapp');

Mongoose Documentation: Connections

And mongoose creates the collection with a plural name.

If you have a model with Tank name, the collection name will be tanks:

var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

Mongoose Documentation: Model

like image 88
Marcus Vinicius Sousa Vieira Avatar answered Sep 23 '22 11:09

Marcus Vinicius Sousa Vieira


I'm not 100% sure but you also need to create a record so that it creates the database. Only specifying the database name on the connection string isn't enough apparently.

Cheers

like image 29
Pedro Nunes Avatar answered Sep 22 '22 11:09

Pedro Nunes