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

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


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.


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