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?

Yogesh Devgun
  • 1,297
  • 1
  • 19
  • 36
Purva chutke
  • 131
  • 1
  • 1
  • 3

2 Answers2

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.

Neeraj Sewani
  • 3,952
  • 6
  • 38
  • 55
vmr
  • 1,895
  • 13
  • 24
  • 2
    but how can we restrict this automatic creation of collection. As don't want it. – Purva chutke Aug 21 '14 at 05:46
  • 2
    That is how mongoose works, you cannot restrict it. Refer this link : http://mongoosejs.com/docs/guide.html – vmr Aug 21 '14 at 08:28
  • Use Spring Data instead. Because :extensive documentation and large developer community. – vmr Aug 21 '14 at 09:57
  • From 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." – ObjectiveTC Aug 05 '17 at 02:00
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

Mrchief
  • 75,126
  • 20
  • 142
  • 189