What is the best way to execute a method within a mongoose schema when retrieving a full list from a model?

I have created a method on my mongoose model like so -

PatientSchema.methods.calculateAge = function(){
    let ageDifferenceInMs = (Date.now() - this.dateOfBirth.getTime());
    let ageDate = new Date(ageDifferenceInMs);
    let age = Math.abs(ageDate.getUTCFullYear() - 1970);
    return age;
}

It works perfectly when I retrieve a single instance of the related model. However, my question is how can I add a new key-value pair in a JS object where the value is generated using a method defined in the model when retrieving multiple instances like this -

const patientList = await Patient.find({})

I could do it using a loop, but I'm wondering if there's a more optimized way to achieve this.

UPDATE - As suggested by @Milad Raeisi, I implemented virtuals like this-

PatientSchema.virtual('age').get(function () {
    let temp = new Date(this.dateOfBirth)
    let ageDifferenceInMs = (Date.now() - temp.getTime());
    let ageDate = new Date(ageDifferenceInMs);
    return Math.abs(ageDate.getUTCFullYear() - 1970);
})

Don't forget to include

mongoose.set('toJSON', { virtuals: true });

Although this works perfectly for a single instance, it returns null for multiple instances.

This is the code snippet I used to get the patient list -

const patientList = await Patient.find({})
            .sort({name:1})
            .limit(limit)
            .skip(skipIndex)
            .select(['name', 'gender', 'age'])
            .exec();

Answer №1

If you're aiming for efficiency, consider utilizing an aggregation query or caching the age data to optimize performance. Alternatively, you can leverage mongoose virtuals to calculate age within a virtual field.

Explore this resource

Edit:

It's important to note that retrieving age from mongoose is unnecessary as it's a virtual field and not stored in the database. To enable mongoose to calculate age in the virtual field, ensure dateOfBirth is included in the select statement.

Give this a try:

const patientList = await Patient.find({})
        .sort({name:1})
        .limit(limit)
        .skip(skipIndex)
        .select(['name', 'gender', 'dateOfBirth'])
        .exec();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transfer PHP variables into a JavaScript array for dynamic data population

Similar Question: Dynamic Pie Chart Data in Javascript and PHP This snippet of code is utilized for populating a pie chart using javascript: <script type="text/javascript"> var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14 ...

Three.js: Plane visibility fluctuates with time

I've been working on a Three.js project where I created a rotating plane. However, I encountered an issue where the plane doesn't display half of the time. To better illustrate this problem, I have created a demonstration in this fiddle. ...

Issue with printing JavaScript value using Selenium_ASSUME_WE_NOT have any changes in the content

I'm currently running tests with Selenium and Java. I've experienced success in printing the pages' HTML from JavaScript by using an alert: js.executeScript("alert($('html').html());"); However, when trying to use return, nothing ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

How to Retrieve JSON Response in Link Function within AngularJS Directive

I have decided to implement a chart library called Plotly in my project. To ensure reusability, I am creating a directive in AngularJS that will allow me to easily integrate the library in the future. The directive will receive an object as input to creat ...

React application not displaying element properly?

I am facing an issue with my react modal that displays a sign-in and sign-up form. The problem arises when I try to access the button on the form using its id, which is modal-sign-in-submit-button. document.getElementById('modal-sign-in-submit-button ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Leveraging electron-usb alongside electron

I attempted to integrate the electron-usb library into my electron project. Upon running npm start with require('electron-usb') in my index.html file, an error is displayed in the console: Uncaught Error: The specified procedure could not be fo ...

Utilizing a loop for setting variable values in JavaScript

Using both JavaScript and JQuery. Let's imagine there is an array called ListArray with various sentences inside. Sounds easy enough. Is there a way to achieve this? var List = for (var i = 0; i < 10; i++) { //iterate over an array here to c ...

When the window is resized, Div escapes from view

My issue is that whenever I resize the browser, the div moves out of the window. I am using the jQuery scroll to plugin for navigating through divs. Oddly enough, when I resize the #home div, everything seems to work fine. However, when I resize other divs ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

What is the best way to manage returning to the original page that was loaded when utilizing the History API?

I'm in a bit of a pickle here. I've been using History.js with the History API and everything was going smoothly until I encountered an issue. Let's start with a simple page setup like this: <div ="header"> Header </div> <d ...

A Sparkling occurrence that is activated upon the completion of plot rendering

I am looking for a way to detect when the plots in a Shiny dashboard tab have finished rendering so that I can hide a loading page element. Currently, I am using the following code: observeEvent("plot", hide(id = "loading-content", anim = TRUE, animType = ...

Creating and deleting HTML elements in a dynamic array format

My current approach involves utilizing jQuery and JavaScript for the purpose of dynamically adding and removing HTML elements. Specifically, I am focusing on the removal of particular HTML elements. The code snippet is as follows: $(document).ready(fun ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...

Receiving blank response when trying to access server variable on the client side

Query: On the server side, I set the value of SessionData(EmployeeID) = "12345", which is first executed during page_load. Later, on the client side: function getEmployeeId() { return "<%# SessionData("EmployeeID")%>"; } When I use th ...

Custom directives are designed to receive arrays as string inputs

I've encountered an issue with my custom directive that has an isolated scope. When I pass an Array variable to the directive, it is being treated as a String inside the directive. This is how my directive looks: angular.module('my.directives& ...

Improving Insert Speed in MongoDB: Tips for Optimizing Insert/sec Performance with mongoimport and --upsert

I am running the following command: mongoimport -h m3 -d staging -c coll --upsert --upsertFields name < part1 The machine I have installed mongoDB 64-bit on shows a decrease in upsert performance over time, starting at 433/second and dropping to 32/se ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

Rearrange JavaScript Object in a Custom Sequence

Looking to filter a JSON Object (Array of Arrays) with a specific order requirement: order: ['Hors','TTC','Total général', 'verger', ' Tra'] data = [[" Tra", "100 - 149 ch", "Total"] [" Tra", "150 - 199 ...