MongoDB updates may not take effect immediately

I am attempting to include a User object in the "players_list" field of my Game object, which is essentially a list of User objects. Let's take a look at how my Game object is structured:

{ players_list:
   [ { games: [Array],
       _id: '5b0e112ff13033792f08566f',
       email: 'c',
       password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
       handle: 'C',
       __v: 0,
       id: '5b0e112ff13033792f08566f' } ],
  _id: '5b0e181aeb766e7bfaf2fb09',
  players_status:
   [ { _id: '5b0e181aeb766e7bfaf2fb0a',
       playerId: '5b0e112ff13033792f08566f',
       status: 'Joined' } ],
  postGameEvaluation: [],
  date: 'QQQQ',
  time: 'QQQQ',
  duration: 4,
  players_needed: 4,
  max_players: 4,
  level: 4,
  author:
   { games:
      [ '5b0e13e69d35007a147578da',
        '5b0e15b4b117987b00d68cb4',
        '5b0e181aeb766e7bfaf2fb09' ],
     _id: '5b0e112ff13033792f08566f',
     email: 'c',
     password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
     handle: 'C',
     __v: 0,
     id: '5b0e112ff13033792f08566f' },
  __v: 0 }

Now, let's take a closer look at my User object:

{ games: [],
  _id: 5b0e1820eb766e7bfaf2fb0b,
  email: 'f',
  password: '$2a$10$JmS.9axW8batMUKzE7OQx.GShdNDt09eArXfYGoI/DUWEKVwAn5ju',
  handle: 'F',
  __v: 0 }

In order to add the User object to the "players_list" field of the Game object, I execute

req.body.players_list.push(req.user)
. This updates the req.body with the new User object included in the player_list field of the Game object as shown below:

{ players_list:
   [ { games: [Array],
       _id: '5b0e112ff13033792f08566f',
       email: 'c',
       password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
       handle: 'C',
       __v: 0,
       id: '5b0e112ff13033792f08566f' },
     { games: [],
       _id: 5b0e1820eb766e7bfaf2fb0b,
       email: 'f',
       password: '$2a$10$JmS.9axW8batMUKzE7OQx.GShdNDt09eArXfYGoI/DUWEKVwAn5ju',
       handle: 'F',
       __v: 0 } ],
  _id: '5b0e181aeb766e7bfaf2fb09',
  players_status:
   [ { _id: '5b0e181aeb766e7bfaf2fb0a',
       playerId: '5b0e112ff13033792f08566f',
       status: 'Joined' } ],
  postGameEvaluation: [],
  date: 'QQQQ',
  time: 'QQQQ',
  duration: 4,
  players_needed: 4,
  max_players: 4,
  level: 4,
  author:
   { games:
      [ '5b0e13e69d35007a147578da',
        '5b0e15b4b117987b00d68cb4',
        '5b0e181aeb766e7bfaf2fb09' ],
     _id: '5b0e112ff13033792f08566f',
     email: 'c',
     password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
     handle: 'C',
     __v: 0,
     id: '5b0e112ff13033792f08566f' },
  __v: 0 }

However, upon updating the Game object in MongoDB using

Post.findByIdAndUpdate(req.params.id, req.body).then((result) => {...
, the resulting update does not reflect the addition of the new User. The updated result is depicted below:

{ players_list: [ 5b0e112ff13033792f08566f ],
  _id: 5b0e181aeb766e7bfaf2fb09,
  players_status:
   [ { _id: 5b0e181aeb766e7bfaf2fb0a,
       playerId: '5b0e112ff13033792f08566f',
       status: 'Joined' } ],
  postGameEvaluation: [],
  date: 'QQQQ',
  time: 'QQQQ',
  duration: 4,
  players_needed: 4,
  max_players: 4,
  level: 4,
  author: 5b0e112ff13033792f08566f,
  __v: 0 }

What caught my attention was that after navigating away from and returning to my current React Component (triggering fetchUser and fetchGame), the refreshed Game now includes the new User in its players_list. Could this be due to the asynchronous nature of the mongo update function? In any case, I assumed that the use of .then((result) => { within

Post.findByIdAndUpdate(req.params.id, req.body).then((result) => {
would ensure that the execution sequence waited for Post.findByIdAndUpdate to complete before proceeding.

Answer №1

If you take a look at the documentation provided in this link: http://mongoosejs.com/docs/api.html#findbyidandupdate_findByIdAndUpdate you will see that findByIdAndUpdate method returns the original object, not the updated document. In order to get the updated object as a result, you need to include {new: true} as options when calling the method.

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

Is there a solution for the issue of a background image loading full-size before being resized in Javascript?

I am currently working on a project where an image is dynamically resized to fit the window using javascript. However, there is an issue where the full-size image is loaded before resizing it, causing a noticeable jump from full-size to resized version. Is ...

Here is a unique rewrite of the text: "Learn how to use JavaScript or jQuery to generate a new table containing only rows that do not have a td element with a colspan attribute

Is there a way to filter a table using javascript or jquery to only return rows that do not contain td elements with a colspan attribute? <table> <tr> <td> text1 </td> <td> text2 </td> </tr> <tr&g ...

Experiencing discrepancies between values retrieved from Mongoose and MongoDB, even though identical syntax is being employed

Using the same syntax in both mongoose and mongo shell is resulting in different values Main data: "username" : "developer2", "createdProjects" : [ ], "registeredClasses" : [ ], "friendRequest" : [ { "id" ...

Whenever attempting to choose a rating, the MUI dialog continuously refreshes and resets the selected rating

I'm facing an issue with my MUI dialog where it keeps refreshing and resetting the selected rating every time I try to rate a movie. Any assistance on this matter would be highly appreciated. The RateWatchMovieDialog component is designed to display ...

Utilizing JQuery to iterate through and display coordinate data

I am trying to calculate the coordinates around a circle, but I'm having trouble getting it to display the coordinates and I'm not sure if it's actually calculating them. Here is my current code: HTML: <p>Displaying coordinates here: ...

Tips for resolving the error "Cannot use import statement outside a module" in situations where you are unable to specify module type in the package.json file

I've been working on a Create-React-App project using normal JS (.jsx) and not TypeScript. During the process, I needed to make changes to some build files by replacing references to local files with live ones. That's when I came across the npm p ...

When two zeros are adjacent, the test fails - Leetcode problem 283: Moving Zeroes

I encountered an issue while working on the leetcode 283 move zeroes problem where I faced a strange test failure when there are two zeros next to each other. Here is the code snippet I used: /** * @param {number[]} nums * @return {void} Do not return ...

Guide on how to retrieve the vertex information once an object is loaded using the ObjLoader in Three.js

When using ObjLoader in Three.js to load a *.obj file into my scene, everything works fine. However, I'm uncertain on how to manipulate the object's vertices and indices individually. How can I access the vertices of the loaded *.obj model? Atte ...

Move a button using jQueryUI

HTML code resides below <!doctype html> <html> <head> <title>jQuery UI: Alphabet Matcher</title> <link href="css/normalize.css" rel="stylesheet"> <link href="matchalphabate.css" rel="styl ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Query the MongoDB C# driver using a string field to search for a specific string argument

mysql information: { name: "aaa" } C# query: string arg = "bbb aaa ccc"; var matches = from x in collection.AsQueryable<BBB>() where arg.Contains(x.name) select x; I understand it may not work as expected. What steps ca ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

jQuery's z-index feature is malfunctioning

When I hover over my menu, a box fades in. However, there is a small icon behind this box that I want to move to the front so it can be visible during hover. To see an example of my menu, click here: Navigation I attempted to address this by using jQuer ...

"Use eslint to manage the integration of typescript with modules, regardless of type declarations

I'm in the process of upgrading eslint to v9 to work with next-json While following the official Getting started guideline, I realized that I need to include "type": "module" in the package.json file for it to function properly. ...

Simplify table structure

I need to reorganize a table structure like the following: Parent Child Value 1 Color Red 1 Height 11 1 Width 12 1 Length 11 2 Color Blue 2 Height 10 2 Width 2 2 Length 5 In order to achieve ...

Utilize service codes from one application within another App in Angular 8

Can a singleton service be created within a "common-components" app and then accessed by another angular application? This service would handle CRUD operations that are used across all applications. We are managing five Angular 8 applications in a microse ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...

Is there a way to deactivate tabs in Bootstrap?

Is there a way to deactivate tabs in Bootstrap 2.0 similar to how you can disable buttons? ...

Mastering the placement of script tags in your Next.js application with Next Script

I'm in the process of integrating a third-party script into my Next.js website. This particular script adds an iframe right below its corresponding script tag. Therefore, it is crucial for me to have precise control over the placement of the script ta ...

Pattern for regex to match the following example: test test123

Regular expression pattern for the test example "test test123". The first string should consist of only alphabets (A-Za-z), while the second string should be a combination of alphabets and numbers (A-Za-z0-9). Examples: 1. hello world123 (true) 2. 123 hel ...