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:
// Importing mongoose module const mongoose = require( "mongoose" )
// Database Address const url = "mongodb://localhost:27017/GFG"
// 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: