Khalid Taha
Khalid Taha

Reputation: 3313

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

Upvotes: 15

Views: 19051

Answers (3)

Suresh Bhatt
Suresh Bhatt

Reputation: 1

Without defining the model, I don't think we can create a new database in Mongoose.

For those facing similar issues-> If you're following MVC architecture, please import the schema/model from the source where database Schema/Models are created, this would solve the issue, or create Schema model in this file itself similar to below:

Sample code to create in the same file for solving such issues:

// Import mongoose

const mongoose = require('mongoose')

// Create Schema - ignore if you've already defined.

const userSchema = new mongoose.Schema({
  firstName: {type:String}, lastName: {type:String}
})

// Then connect this Schema with Model

const userModel = mongoose.model('modelNameHere', userSchema)

// Then connect with database as the above code. 

Upvotes: 0

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

Upvotes: 12

Pedro Nunes
Pedro Nunes

Reputation: 412

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

Upvotes: 25

Related Questions