Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 272
Purva chutke Avatar asked Aug 20 '14 12:08

Purva chutke


People also ask

Does MongoDB automatically create Collection if not exists?

Create a CollectionIf a collection does not exist, MongoDB creates the collection when you first store data for that collection.

Does MongoDB create collection automatically?

You can check the created collection by using the command show collections. In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

Does Mongoose automatically create a collection?

Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name.


1 Answers

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.

like image 171
vmr Avatar answered Sep 23 '22 07:09

vmr