Mongoose Schemas Instance methods
Last Updated :
02 Nov, 2022
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Instance methods refer to the methods used by Mongoose documents. These methods can be both, built-in and custom.
Creating node application And Installing Mongoose:
Step 1: Create a node application using the following command:
mkdir folder_name
cd folder_name
npm init -y
Step 2: After creating the ReactJS application, Install the required module using the following command:
npm install mongoose
Project Structure: It will look like the following.
Example 1: In this example, we will create a custom mongoose instance method to show all the documents with the type “dog”.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log( 'Connected to database' ));
const animalSchema = new mongoose.Schema(
{ name: String, type: String }, {
methods: {
findSimilarTypes(cb) {
return mongoose.model( 'Animal' ).find(
{ type: this .type }, cb);
}
}
}
);
const Animal = mongoose.model( "Animal" , animalSchema);
const animals = [
{
name: 'bond' ,
type: 'dog'
},
{
name: 'cavine' ,
type: 'cat'
}
]
const dog = new Animal({ type: 'dog' });
Animal.insertMany(animals, (err, res) => {
dog.findSimilarTypes((err, dogs) => {
console.log(dogs);
});
})
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Example 2: In this example, we will create a custom mongoose instance method to show all the documents with the type “cat”.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log( 'Connected to database' ));
const animalSchema = new mongoose.Schema({ name: String, type: String }, {
methods: {
findSimilarTypes(cb) {
return mongoose.model( 'Animal' ).find({ type: this .type }, cb);
}
}
}
);
const Animal = mongoose.model( "Animal" , animalSchema);
const animals = [
{
name: 'bond' ,
type: 'dog'
},
{
name: 'cavine' ,
type: 'cat'
}
]
const cat = new Animal({ type: 'cat' });
Animal.insertMany(animals, (err, res) => {
cat.findSimilarTypes((err, cats) => {
console.log(cats);
});
})
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Reference: https://mongoosejs.com/docs/guide.html#methods
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...