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

15,119

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

Share:
15,119
Purva chutke
Author by

Purva chutke

Updated on June 14, 2022

Comments

  • Purva chutke
    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
    Purva chutke almost 10 years
    but how can we restrict this automatic creation of collection. As don't want it.
  • vmr
    vmr almost 10 years
    That is how mongoose works, you cannot restrict it. Refer this link : mongoosejs.com/docs/guide.html
  • vmr
    vmr almost 10 years
    Use Spring Data instead. Because :extensive documentation and large developer community.
  • ObjectiveTC
    ObjectiveTC almost 7 years
    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."