Mongoose Schemas Virtuals
Mongoose Schemas Virtuals are document attributes that only exist logically and are not written to the document’s collection in the MongoDB database. They do not persist or get stored there. When we access the virtual property, Mongoose calls the get method. Virtual property setters are applied before other validation.
Syntax:
schema({
virtuals: {
propertyName: 'Program Logic'
}
});
Parameters:
- propertyName: It is the name of the property which you want to define.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.
npm install mongoose
After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
Example 1: The below example illustrates the functionality of the Mongoose Schema virtuals property. In this example, we have defined a virtual named fullName on schema which will return a string. We will define the virtuals using this example schema options.
Javascript
const mongoose = require( 'mongoose' );
mongoose.set( 'strictQuery' , false );
mongoose.connect(url)
.then((ans) => {
console.log( "Connected Successful" )
})
. catch ((err) => {
console.log( "Error in the Connection" )
})
const Schema = mongoose.Schema;
const schema = new Schema({
firstName: {
type: String,
require: true ,
},
lastName: {
type: String,
require: true ,
}
},
{
virtuals: {
fullName: {
get() {
return this .firstName +
' ' + this .lastName;
}
}
}
});
const Person = mongoose.model( 'Person' , schema);
const person = new Person(
{ firstName: 'Sam' , lastName: 'Snehil' }
);
console.log(
'FullName without concatenation: ' ,
person.firstName + ' ' + person.lastName);
console.log(
'Full Name with virtuals: ' + person.fullName
)
|
Output:
FullName without concatenation: Sam Snehil
Full Name with virtuals: Sam Snehil
Connected Successful
Example 2: The below example illustrates the functionality of the Mongoose Schema virtuals. In this example, we will define the virtuals using the virtual method.
Javascript
const mongoose = require( 'mongoose' );
mongoose.set( 'strictQuery' , false );
mongoose.connect(url)
.then((ans) => {
console.log( "Connected Successful" )
})
. catch ((err) => {
console.log( "Error in the Connection" )
})
const Schema = mongoose.Schema;
const schema = new Schema({
name: String,
address: String,
});
schema.virtual( 'Introduce' ).get((a, b) => {
return this .name + ' is from ' + this .address;
})
.set((v) => {
let temp1 = v.split( ' ' );
this .name = temp1[0];
this .address = temp1[1];
})
const Person = mongoose.model( 'Person' , schema);
const person = new Person({});
person.Introduce = 'Sam NewDelhi' ;
console.log(person.Introduce)
|
Output:
Sam is from NewDelhi
Connected Successful
Reference: https://mongoosejs.com/docs/guide.html#virtuals
Last Updated :
11 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...