Mongoose issue with updating a field within a subarray object

I'm facing some issues while updating a field in my mongoose model. My intention is to locate a specific username within a list of friends in a user model and then proceed to update a field within the same object that contains the corresponding username.

Below is the code snippet I've tried, however, the status field doesn't seem to update as expected:

router.post('/profile/:id/friendRequest/:username', authenticateUser)
router.post('/profile/:id/friendRequest/:username', async (req, res) => {
  const { id, username } = req.params;
  const { status } = req.query;

  try {
    const user = await User.findOneAndUpdate({_id: id, 'friends.username': username},  {$set: 
    {'friends.$.status': status}}, {new:true, upsert: true}).exec();
  
      res.json({
        friends: user.friends,
        success: true,
        loggedOut: false,
      })
    } catch (err) {
      catchError(res, err, 'Invalid user id');
    }
});

The section of my schema where I am attempting to update the status is outlined below:

User({
    friends: {
    status: Number,
    username: String,
    state: String
  }
});

I would greatly appreciate any guidance or assistance to help me progress in the right direction.

Answer №1

According to the information provided in the set reference, it is suggested to utilize "friends.status" within the second parameter. When using "friends.$.status", the system will specifically search for the status attribute within the $ property of friends.

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

Adding a mongoose document to an array by using the push

I am facing an issue while trying to push an object into an array in the database. I found a related topic on Stack Overflow but I am having trouble implementing it Push items into mongo array via Mongoose habalka.files.push({_id: "tata", destination: "Ha ...

The <Button> element is incompatible with popups. (HTML, CSS, JS)

I've been struggling with this issue. I used CSS color values to create a smiley face, but when I added a button it messed up the design (adding an unwanted circle around the center of the smiley). I attempted to synchronize the button tag with the po ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

Run a function after all xmlHttpRequests have finished executing

OVERVIEW My website relies on an API to fetch data, making multiple post and get requests to a server upon opening. While we know how long each individual call takes, determining the total time for all calls to complete is challenging. SCENARIO For inst ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

How can one effectively eliminate redundant duplicates from an object in Javascript?

Review the JavaScript object provided below (note that only a portion of the object is shown). https://i.sstatic.net/5H0gn.png Here is the requirement: For each distinct user, limit the number of random leads to a maximum of 4 and discard the rest. For ...

Improving the code of a JavaScript compiler through refactoring

I recently delved into the intricacies of a JavaScript package compiler and decided to revamp its fundamental structure. Each time a string is compiled, it gets appended to the SrcTable array and then outputted. However, for the output to be obtained, the ...

What is causing the ERR_HTTP_HEADERS_SENT('set') error when running on Windows Server, but not on my development machine?

Currently, I am in the process of developing a Node/Express application that will integrate with ActiveDirectory. The login form is designed to post the username and password to a specific /auth route, where the AD authentication takes place, along with se ...

Can anyone provide guidance on how to make slideToggle move upwards with jQuery?

<div class="row"> <div class="col-lg-2" ></div> <div class="head" style="background-color: #1c94c4; text-align: center; cursor: pointer;"> Connect</div> <div class="chat" style="display: none;width:a ...

Challenges in the Knockout Framework Due to Synchronization Issues

Recently, I've encountered a slight problem with race conditions in my code. Utilizing Knockout.Js to collect information for user display has been the cause. The issue arises when a dropdown needs to be created before a value can be selected. Typica ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...

NodeJS - Issue: The procedure specified could not be located in the bcrypt_lib.node

After upgrading from Node.js 0.12.7 to 4.2.1, I encountered an error when attempting to start my server: $ node server.js C:\Users\me\documents\github\angular-express-auth\node_modules\bcrypt\node_modules\bindi ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Ways to retrieve the file name and additional attributes from a hidden input type

Is it possible to access the file name and other attributes of a hidden file when submitting it using the <input type="hidden"> tag? My current project involves drag and drop file functionality on a server using Node.js. If I am able to dynamically ...

Tips for creating canvas drawings in GWT

Here's a simple jQuery code to draw a triangle in a canvas element that is 40 by 40: var context1 = $("#arrow_left").get(0).getContext('2d'); context1.beginPath(); context1.moveTo(25,0); context1.lineTo(0,20); context1.lineTo(25,40); contex ...

Upon refreshing the browser, an error pops up saying "unable to set headers after they have been sent."

Error image: https://i.sstatic.net/3dnH9.png app.get('/home', function (req, res, next) { usersession = req.session; if (usersession.loggedin == true) res.redirect('/home'); res.sendFile(path.join(__dirname, &a ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

Vue Router is not updating the router view when the router link clicked is embedded within the view

I have a section called Related Content located at the bottom of my posts page, which displays other related posts. When I click on the Related Content, I expect the router to update the page. However, it seems that although the URL changes, the view does ...