Skip to content
Related Articles

Related Articles

Mongoose mongoose.model() Function

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 05 Feb, 2021
Improve Article
Save Article

The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.


mongoose.model(<Collectionname>, <CollectionSchema>)

Parameters: This function accepts the following two parameters:

  • Collection name: It is the name of the collection.
  • Collection Schema: It is the schema of the collection.

Return type: This function returns the Mongoose object.

Installing Module: Install the mongoose module using the following command:

npm install mongoose

Project Structure: Our project structure will look like this:

Running the server on Local IP: Data is the directory where MongoDB server is present.

mongod --dbpath=data --bind_ip

Filename- index.js:


// Importing mongoose module
const mongoose = require("mongoose")
// Database Address
// Connecting to database
mongoose.connect(url).then((ans) => {
}).catch((err) => {
  console.log("Error in the Connection")
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
  name: {
    type: String,
    require: true
  marks: {
    type: Number,
    default: 0
// Creating collection
const collections = mongoose.model("GFG", collection_structure)
// Inserting one document
  name: "aayush",
  marks: 10
}).then((ans) => {
  console.log("Document inserted")
}).catch((err) => {

Run index.js file using below command:

node index.js


MongoDB Database: Our database after executing the above command will look like this:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!