MongooseJs Virtual Properties with NodeJs, MongoDB

In the tutorial, we show how to use MongooseJs Virtual Properties with NodeJs, MongoDB.

Related Posts:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
NodeJs/Express MongoDB One-to-Many related documents
Mongoose Many-to-Many related models with NodeJS/Express, MongoDB

Mongoose Virtual Property

We define a customerSchema as below:

How to get a customer’s fullname?
-> With traditional way, we can do as below:

Problems?
-> The above way is too cumbersome. We can use a new approach with Mongoose Virtual property.

Mongoose Virtual Properties are document properties that we can get and set but Not persisted to MongoDB.
– To combining fields, we use getters
– To de-composing a single value into multiple values for storage, we use setters

Now, see the executing of below code:

Note: ‘fullname’ will not be persisted to MongoDB. So we can NOT use virtual properties for building queries and field selection.

For saving bandwidth, we can use Aliases type of Virtual properties. With Aliases, we can make a readable name from a short property name which stored in MongoDB:

Now, see the results of below code:

Practice

Create NodeJs project

Following the guide to create a NodeJS/Express project.

Install Express/Mongoose by commandline:

-> ‘package.json’ :

Customer Schema

Config MongoDB

Implement Express Server

Sourcecode

NodeJs-Mongoose-Virtual-Property

Run NodeJs App by commandline: node server.js
-> Results:

mongoose-virtuals-properties-alias-app console logs

mongoose-virtuals-properties-alias-mongodb-records

By JavaSampleApproach | April 15, 2018.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*