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
const mongoose = require("mongoose")
mongoose.connect(url).then((ans) => {
console.log("ConnectedSuccessful")
}).catch((err) => {
console.log("Error in the Connection")
})
const Schema = mongoose.Schema;
const collection_structure = new Schema({
name: {
type: String,
require: true
}
,
marks: {
type: Number,
default: 0
}
})
const collections = mongoose.model("GFG", collection_structure)
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
Share your thoughts in the comments
Please Login to comment...