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?
Create a CollectionIf a collection does not exist, MongoDB creates the collection when you first store data for that collection.
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.
Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With