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

3

13

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?

Jerricajerrie answered 20/8, 2014 at 12:53 Comment(0)
S
18

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.

Swatter answered 20/8, 2014 at 13:30 Comment(4)
but how can we restrict this automatic creation of collection. As don't want it.Jerricajerrie
That is how mongoose works, you cannot restrict it. Refer this link : mongoosejs.com/docs/guide.htmlSwatter
Use Spring Data instead. Because :extensive documentation and large developer community.Swatter
From the 'guide' link that @Swatter 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."Regretful
S
5

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

Smasher answered 2/4, 2019 at 20:43 Comment(0)
D
0

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.

Donall answered 9/8 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.