The latest entries are not visible on Mongoose unless the page is refreshed

There is a router with handlers for GET and POST requests related to documents. When creating new documents and posting them, the redirection works smoothly. However, upon initial page load after creation, only existing documents are displayed. It's only upon refreshing the page that the newly created documents appear. Any insights on why this happens and how to resolve it?

Answer №1

The issue within your code arises from not allowing the update function to finish before proceeding. :) When you instruct the database to save the documents using:

Document.update({'_id': doc.id}, d, {overwrite: true}...

Since mongo performs updates asynchronously, this code will only query and move on without waiting for the actual update to occur. To rectify this, it is essential to execute res.redirect('/documents'); in the callback function (which executes after the update completes). Therefore, your revised code should resemble the following:

Document.update({'_id': doc.id}, d, {overwrite: true}, function(err, raw) {
   if (err) return handleError(err);
   res.redirect('/documents');
});

Here is an example of Promise.all as requested by @XavierB

//Gather all promises into a single array
let promises = [];
promises.push(Document.update({'_id': doc.id}, d, {overwrite: true}));
//Wait for all promises to resolve
Promises.all(promises).then(function(){
    //All promises have resolved successfully
    res.redirect('/documents');
}).catch(err => { 
    //An error occurred with any of the promises.
    console.log(err); 
});;

Answer №2

Executing this function asynchronously may result in a delay before completion. To ensure proper execution, consider utilizing async/await or .then to trigger the redirect to '/' within the callback function.

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

What is preventing this Node JS code from successfully serving a static PNG file?

To the administrators, I have spent hours scouring various resources for answers related to Node Js, Express, and serving static files. Despite my efforts on stackoverflow and other platforms, I have yet to find any solution that works for me. If my questi ...

Encountered a problem while trying to run expo build:ios on a Windows machine for a React

Currently, I am working on developing an IOS edition of my React Native App using Expo CLI. However, during the process, I came across the following error: error Has anyone faced this particular issue in the past? While the Android version of my app was ...

Using regular expressions, divide the string at every occurrence of a period unless there is a quotation mark immediately following the period, in which case

Can anyone help me split this string? It includes quotation marks: "This is a test. I need this to be splitted." And here is one with a question? I am looking for: ['"This is a test.', 'I need this to be splitted."' ...

A step-by-step guide on generating an EJS file dynamically directly from a database

Hi there, I am a new web developer and currently working with Mongo/Express/Node stack. My current project involves creating an e-commerce site where the admin can add new "categories" to the database. Whenever a new category is added, I want to dynamical ...

Unable to load files in Handlebars when using Node and Express

Currently, I am in the process of developing a Node/Express web application for basic CRUD operations. However, I am encountering difficulties incorporating Handlebars into my project. Whenever I attempt to utilize Handlebars, none of the stylesheets from ...

Is it possible to link together npm configuration entries?

Utilizing the npm config section is straightforward and innovative, but I have encountered a limitation: configurations cannot be expanded to chain values or access non-config variables such as package version. For example: { "name": "myproj", "versi ...

Issues persist while attempting to save sass (.scss) files using Atom on a Mac

When attempting to work with sass files, I encountered an error message every time I tried to save the file: Command failed: sass "/Users/bechara/Desktop/<path of the file>/test.scss" "/Users/bechara/Desktop/<path of the file>/test.css" Errno: ...

"Why does Mocha not display detailed information about passed tests like Jest does? Instead of providing specific details, it only shows a message saying 5 tests passed

Even though I am new to mocha, I have experience with jest. When I run my tests in mocha, I expect to see a comprehensive log but all it displays is 9 tests passed. I'm using the nyan reporter. Attached below is a screenshot for reference: ...

Using Socket.io and Express for Clustering: A Beginner's Guide

When using express with socket.io and express-session along with express-socket.io-session, I am able to seamlessly connect the session to my socket instance. Below is the code snippet I utilized for clustering: var cluster = require('cluster') ...

Using Node and Express to Serve Multiple Rendered Views in a Single Response

I'm making an AJAX request and I want to receive a JSON response containing multiple partial views that I can use to update different sections of my page. For example: { "searchResults": "<div>Some HTML string</div>", "paginationB ...

Encountered an error while attempting to log in: TypeError: the property 'id' of null cannot be read

I am facing an issue with the login process, specifically getting a TypeError: Cannot read property 'id' of null error message. How can I debug and resolve this error? var cas = require('cas-client'); get_forward_url(function(forwardur ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Executing an Asynchronous Fetch Request within a Next.js API Route (Application Router)

I have encountered an issue while making a fetch request from an API route in Next.js 13 (App Router). I want to dispatch the request without blocking it, but for some reason, the fetch request does not fire unless I put an "await" at the start of it. My ...

Preventing unauthorized access to files in ExpressJS public directories

Is there a way to conceal files served by the Node server? Despite my attempts to redirect certain files and directories, Express 4.X does not seem to cooperate. I have also experimented with sending 4XX HTTP responses when specific files are requested, bu ...

Building Your Initial HTTP Server using Node.js

Hey everyone, I'm relatively new to node.js but have made some progress. Following the steps in this tutorial, I was able to create my first "example" server. However, there are a few things that I don't quite understand. Could someone please exp ...

Steps to sending a GET request using the MERN (MongoDB, Express,

I'm currently attempting to retrieve data from a database. The only information I received in the response is: Response {type: "cors", url: "http://localhost:5000/products/", redirected: false, status: 200, ok: true, …} I requ ...

Rendering server applications using Angular 6 with Express

Currently, I am working with an Angular 6 application and Express server. I am looking to implement a server rendering system using the best practices available, but I have been struggling to find resources that are compatible with Angular 6 or do not util ...

Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router. In my server.js file, I have the following setup: app.use('/user/:id/profile', require('./routes/profile')); Within my ./routes/profile.js fil ...

A streamlined method to verify the presence of a username or email address in MongoDB before registering

I'm currently running a NodeJS server with ExpressJS to manage my /register route. As part of the registration process, I need to confirm that both the user's username and email are unique before allowing them to create an account in the users co ...

tips for successfully transferring date and time data between json and nosql databases like firestore

Input: Created_At:Monday, 29 April 2019 15:07:59 GMT+05:30 Updated_At:Monday, 29 April 2019 15:07:59 GMT+05:30 I attempted to export data in JSON format from Firestore using the npm package firestore-export-import. However, the output I received was: ...