How to create a collection automatically in mongoDB if it's not already there?
Solution 1
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.
Solution 2
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
Purva chutke
Updated on June 14, 2022Comments
-
Purva chutke about 2 years
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?
-
Purva chutke almost 10 yearsbut how can we restrict this automatic creation of collection. As don't want it.
-
vmr almost 10 yearsThat is how mongoose works, you cannot restrict it. Refer this link : mongoosejs.com/docs/guide.html
-
vmr almost 10 yearsUse Spring Data instead. Because :extensive documentation and large developer community.
-
ObjectiveTC almost 7 yearsFrom the 'guide' link that @vmr posted above: "option: collection -- Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. Set this option if you need a different name for your collection."