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

I am creating passport authentication for node using mongoose. I do not have a collection called "users" in my database. But when creating a new user using the scheme as shown 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 create a new collection of "users". How is this possible?

+8
source share
2 answers

Here mongoose will check if the collection named "Users" exists in MongoDB, if it does not exist, then it creates it. The reason is that mongoose adds 's' to the specified model name. In this case, "User" ultimately creates a new collection called "Users" . If you specify the name of the model as "Person" , then in the end she will create a collection of "Person", if the collection with the same name does not exist.

+11
source

Mongoose multiplies the model name and uses it as the default collection name. If you do not need the default behavior, you can specify your name:

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

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

0
source

Source: https://habr.com/ru/post/974097/


All Articles