Altering information in a mongoose callback prior to sending it back in the response

When using the Mongoose package to retrieve data from MongoDB and send it to a browser, I encountered an issue with reassigning a date object to a string. Despite my attempts to change the date object to a string before passing it to the HTML file, it did not get reassigned. I wonder what could be causing this?

I experimented with reassigning it to a different Date() instance, which worked fine. Are there specific schema rules that still apply when accessing or modifying data in a callback function? How can I successfully convert this variable into a string that represents a date?

function index(req, res, next) {
    Flight.find({},function(err, flights){
        flights.forEach(function(flight){
            flight.departs = 'any string';
            console.log(flight.departs);
        })
        res.render('flights/index', {flightDocs: flights, title: 'Flights', moment});
    })
}

The console displays the original date objects retrieved from the database:

2020-11-17T23:56:00.000Z
2019-11-17T22:01:00.000Z
2019-11-17T23:05:00.000Z
2019-11-17T22:03:00.000Z
2020-11-18T00:01:00.000Z
2020-11-18T00:01:00.000Z

Answer №1

flight is not just a regular object; it's a mongoose model. When you call flight.departs, the getter of the model will be invoked to return the value.

If you need to convert a model to a JSON object, you can then edit the new JSON object as required.

function index(req, res, next) {
  Flight.find({}, function (err, flights) {
    const flightsResult = flights.map(function (flight) {
      const json = flight.toJson(); // Convert document to JSON object
      json.departs = 'any string'; // Update JSON property
      console.log(flight.departs);
      return json;
    });
    res.render('flights/index', { flightDocs: flightsResult, title: 'Flights', moment });
  })
}

Alternatively, you can instruct Mongoose to return a plain JavaScript version of the retrieved documents by using lean() in the query chain.

function index(req, res, next) {
  Flight.find({}).lean().exec(function (err, flights) {
    flights.forEach(function (flight) {
      flight.departs = 'any string';
      console.log(flight.departs);
    })
    res.render('flights/index', { flightDocs: flights, title: 'Flights', moment });
  })
}

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

The Redux UI does not refresh when altering the state of a nested array

As someone who is relatively new to Redux, I am facing an issue with my web application which is an eCommerce platform. In this application, users can create multiple carts, each with a unique id and name, and add different items to these carts stored in a ...

Is it possible to attach a mouseup event to the document body using Angular?

I'm working with a jQuery snippet that hides an element when clicked outside of it: jQuery(document).mouseup(function (e) { var container = jQuery('.dropDown'); if (!container.is(e.target) // if the target of the cl ...

Issue with AngularJS $broadcast not functioning when initializing

In the controller, there is HTML button code that attempts to call a specific function on click: <button ng-click="vm.openpopup()" ng-if="!vm.data.length" uib-tooltip="Add Business Value Chain" class="btn btn-default `enter code h ...

Store vueJs data in browser's localStorage

Is there a way to save the state of my game even after a page refresh using local or session storage? I've successfully stored wins in localStorage, but I'm struggling to keep the table with "X" and "O" in the same spot after a refresh. Any sugge ...

Trying out GraphQL resolvers using Jest

I am eager to begin writing tests for a GraphQL resolver using Jest, but I feel lost on how to get started. The resolvers are quite basic CRUD functions that interact with a MongoDB database using mongoose in NodeJS. Schema: type Article { _id: ID! t ...

Updating Angular UI routes with various parameters

When utilizing Angular UI router, I have a route configured in the following manner $stateProvider.state('edit', { url: '/:file/:page', ... } After modifying the route from /edit/file1/page1 to /edit/file1/page2, the view does ...

"Creating a delay within a loop using the setTimeout function

When using setTimeout in a loop, I noticed that all the operations are executed only after the loop ends. I followed the advice from multiple articles and tried putting setTimeout in a separate function, but it didn't make any difference. Here is the ...

There appears to be an issue with 'session' being undefined in this JS/Express/Redis setup for session storage

I've been experimenting with using redis for sessions in my express app. This is what I'm doing: server/auth.js import express from 'express'; import uuid from 'uuid'; const router = express.Router(); router.route(' ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

Select2 using AJAX: chosen option disappears upon receiving AJAX response

Despite going through numerous questions and answers, the issue persists. Here is an excerpt of the code in question: <div class="col-md-2"> <label for="wh_location">{{ __('reports.warehouse_movement.location') ...

MongoTemplate's Criteria for matching all documents

I recently noticed that in Mongosh I am able to use an empty object {} to match all documents. However, when trying to achieve the same thing using Java MongoTemplate API, I couldn't find an equivalent method. The closest solution I came up with is: Q ...

The .prepend() method receives the variable returned by ajax and adds it

I'm facing a challenge with adding a dynamic select box to a string within my .prepend() function. The options in the select box are subject to change, so hard coding them is not an option. To tackle this issue, I am using an AJAX call to construct th ...

Missing support for concatenating multiple fields and querying with date conversion in Monger operators for Clojure

My mongo data set looks like this: {"month": 9, "year": 2015, "name": "Mr A"} {"month": 9, "year": 2015, "name": "Mr B"} {"month": 10, "year": 2015, "name": "Mr B"} {"month": 11, "year": 2016, "name": "Mr B"} I am attempting to find the minimum date from ...

Is it possible to trigger a mouseover event on a background div that is obscured by a foreground tooltip in jQuery?

I created a unique effect where a background div fades in when moused over, followed by the foreground div fading in. However, I encountered an issue where the tooltip ends up "flashing" as the foreground steals focus from the background. For reference, h ...

Having trouble getting an HTML form to function with Ajax and PHP?

Seeking assistance from anyone who can lend a hand. I am delving into the complexities of Ajax, and I'm encountering issues where it seems like the script is being completely ignored or perhaps I'm just making a rookie mistake. Prior to display ...

The issue of receiving a "collection is not a function" TypeError often arises when trying to link MongoDB and NodeJS together

I am a newcomer to MongoDB and currently working on establishing a connection between my ExpressJS server and a MongoDB database. Below is the code I have written for this purpose: const PRIMARY_SERVER = "mongodb://localhost:27017/"; const { M ...

Is there a way to retrieve a collection of files with a particular file extension by utilizing node.js?

The fs package in Node.js provides a variety of methods for listing directories: fs.readdir(path, [callback]) - This asynchronous method reads the contents of a directory. The callback function receives two arguments (err, files), with files being an arra ...

How can a variable be used to assign a date value to an Angular Material datepicker?

Is there a way to modify the date of an item in an array? I've encountered an issue when attempting to input the selected object's date into the Material datepicker. Strangely, it seems to function properly if you manually type in a date as a str ...

Hold on while utilizing Path (Puppeteer)

My current setup involves using Puppeteer 22.6.0 with NodeJS for web scraping purposes. I am facing a challenge where I need to pause the script until a specific h1 element becomes visible on the page. The tricky part is that there are multiple h1 elements ...

Encountering an error when attempting to deploy the highcharts Export Server on the production server, as an issue arises when trying to

An error occurred during auto configuration, with the message: "Auto configuration failed 140718236727232:error:25066067:DSO support routines:DLFCN_LOAD:could not load the shared library:dso_dlfcn.c:185:filename(libproviders.so): libproviders.so: cannot op ...