Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Mongoose mongoose.model() Function

  • Difficulty Level : Hard
  • Last Updated : 05 Feb, 2021

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :