How to use Mongoose virtual property

In this article, you are going to learn about how to use mongoose virtual property. In mongoose, you can use the virtual property. This will…


This content originally appeared on CodeSource.io and was authored by Deven

In this article, you are going to learn about how to use mongoose virtual property.

In mongoose, you can use the virtual property. This will let you work logically on your project. The main benefit of using the virtual property is that it will not persist the document in the MongoDB database. That means you can use and work with your document without manipulating the actual document.

Mongoose virtual property provides a get method that is used to set a specific value of the virtual property from existing document field values. Let’s see an example of using the get method to understand things more clearly. Here, as an example, we will persist a student name separately and print a fullname with the help of using get method.

Mongoose Model

const mongoose = require('mongoose')

const studentSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
})

studentSchema.virtual('name.full')
    .get(function () {
        return this.name.first + ' ' + this.name.last;
    })

const Student = mongoose.model('Student',studentSchema)

module.exports = Student

Here, in our student schema we will save the name separately and after that we use get method. Let’s save a data and see what happens in the MongoDB database.

JavaScript

const mongoose = require('mongoose')
const express = require('express')
const dotenv = require('dotenv')
const Student = require('./Student')
dotenv.config({path:'./config.env'})
const app = express()

// creating student name
const student = new Student({
  name: {
    first: "Deven",
    last: "Rathore"
}
})

// using virtual properties
student.save()
    .then(doc => {
        console.log("Good Morning! ", doc.name.full)
    })
    .catch(error => {
        console.log(error);
    })

// Connecting Database
const DB = process.env.DATABASE.replace('<PASSWORD>',process.env.DATABASE_PASSWORD)
mongoose.connect(DB,{
  useNewUrlParser : true,
  useUnifiedTopology : true
}).then(() => {
  console.log('Database Connected...')
})

// Start servr on a specific port
const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
  console.log(`App is running on port ${PORT}...`);
});

Here, we have used express that is a NodeJS framework and connect our database and also use the virtual property to get a full name of a student. Let’s see the output in the below:

To see the output we run the command node app.js and we can see the full name of the student. Now, let’s check the database if there any changes occurred or not in the below:

In the database, we can see that there is no field document of a full name but we can use it logically in our code. This is how mongoose virtual property works. It is not limited to just printing a full name. The purpose of this article is to make you familiar with the mongoose virtual property. You can do a lot more useful stuff by using mongoose virtual property and to do so you need to follow the mongoose official documentation along with this article with a lot of practice.


This content originally appeared on CodeSource.io and was authored by Deven


Print Share Comment Cite Upload Translate Updates
APA

Deven | Sciencx (2022-01-15T05:27:35+00:00) How to use Mongoose virtual property. Retrieved from https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/

MLA
" » How to use Mongoose virtual property." Deven | Sciencx - Saturday January 15, 2022, https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/
HARVARD
Deven | Sciencx Saturday January 15, 2022 » How to use Mongoose virtual property., viewed ,<https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/>
VANCOUVER
Deven | Sciencx - » How to use Mongoose virtual property. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/
CHICAGO
" » How to use Mongoose virtual property." Deven | Sciencx - Accessed . https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/
IEEE
" » How to use Mongoose virtual property." Deven | Sciencx [Online]. Available: https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/. [Accessed: ]
rf:citation
» How to use Mongoose virtual property | Deven | Sciencx | https://www.scien.cx/2022/01/15/how-to-use-mongoose-virtual-property/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.