Purva chutke
Purva chutke

Reputation: 131

How to create a collection automatically in mongoDB if it's not already there?

I am creating passport authentication for node using mongoose. I don't have any collection called "users" in my database. But while creating new user using the schema like below

var mongoose = require('mongoose');

 module.exports = mongoose.model('User',{
id: String,
username: String,
password: String,
email: String,
firstName: String,
lastName: String
});

It will automatically creates new "users" collection. How is this possible?

Upvotes: 13

Views: 23348

Answers (3)

Kumar Aniket
Kumar Aniket

Reputation: 1

You always need to write collection name in lowercase and collection name must be end with s.Just like cases,logins,singups etc, Not like - Users,Logins,User,Login this is wrong.

Upvotes: 0

Mrchief
Mrchief

Reputation: 76218

Mongoose pluralizes the model name and uses that as the collection name by defualt. If you don't want the default behavior, you can supply your own name:

const UserModel = mongoose.model('User', new Schema({ ... }, { collection: 'User' }));

Ref: https://mongoosejs.com/docs/guide.html#collection

Upvotes: 5

vmr
vmr

Reputation: 1935

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'. If you had specified the model name as 'Person', then it will end up creating a collection called 'Persons' if a collection with the same name does not exist.

Upvotes: 18

Related Questions