The Wayback Machine - https://web.archive.org/web/20240217063942/https://www.geeksforgeeks.org/mongoose-mongoose-model-function/
Open In App
Related Articles

Mongoose mongoose.model() Function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Syntax:

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 127.0.0.1

Filename- index.js:

Javascript

// Importing mongoose module
const mongoose = require("mongoose")
  
// Database Address
  
// Connecting to database
mongoose.connect(url).then((ans) => {
  console.log("ConnectedSuccessful")
}).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
collections.create({
  name: "aayush",
  marks: 10
}).then((ans) => {
  console.log("Document inserted")
}).catch((err) => {
  console.log(err.Message);
})

                    

Run index.js file using below command:

node index.js

Output:

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 05 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads