Add an item to a nested array of objects in a database using the Mongoose push method

When working in this function, I search for the specific post using the postId. Then, within that post, I locate a particular comment based on the commentId. After that, I verify if the array of nested objects likes contains the userId. If not found, I add the userId to the likes array. However, despite following these steps, the userId is still not being added to the likes array. What could be causing this issue?

const likeComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    const comment = post.comments.find(
      (comment) => comment.id === req.body.commentId
    );
    if (comment.likes.includes(req.body.userId)) {
      var index = comment.likes.indexOf(req.body.userId);
      if (index !== -1) {
        comment.likes.splice(index, 1);
      }
      res.status(200).json("you disliked this comment");
    } else {
      comment.likes.push(req.body.userId);
      res.status(200).json("you liked this comment");
    }
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

Answer №1

My solution involves executing post.save();

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

Unable to establish a value within the function

I am encountering an issue where I cannot set a value inside a function. When I attempt to alert this value, it returns as undefined. How can I retrieve this value outside of the function? var startingLatitude; L.esri.Geocoding.geocode() .text(document ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

The recently introduced button following an ajax request fails to trigger the expected event

How can I ensure jQuery still works after adding a new button with AJAX? $('button.btn').on('click', function(form) Here is a sample existing button on initial page load: <button id="5" class="yellow-button btn">Publish</but ...

Navigating through props outside a class component in React

I'm struggling to grasp how I can access props that are defined outside of a React class component. In the code snippet below, all props are clearly outlined except for this.props.checkboxArray, which is currently throwing an error "cannot read prope ...

Concerns with textbox placement while scrolling with an absolute position style

I have an ASP:textbox on a page with various controls and divs, where I am setting the style to position:absolute on the "onkeyup" event. The height of the textbox increases dynamically based on the characters entered, but the issue is that the textbox alw ...

Unable to proceed, WISTIA upload frozen at 100% complete

I recently integrated the Wistia API for video uploads. Everything seemed to be working fine as per the Wistia documentation until I encountered an issue. After uploading a video file, the progress bar would reach 100%, but then an error was logged in the ...

Transform the string response in a websocket message into JSON format

When receiving a websocket message, I often encounter a response in the form of a string like this: odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet", ...

computational method for organizing balls in a circular formation

I need help arranging 10 spheres in a ring using code. So far, this is what I have, but it's not working as expected. const sphereGeometry = new THREE.SphereGeometry(300, 20, 20); const sphereMaterial = new THREE.MeshLambertM ...

Issue in IE11 with pdf.js: src property (0x800a138f)

My application uses pdf.js to display PDF files, and everything works smoothly except for one issue with Internet Explorer. Whenever I try to start the app on IE, an exception is thrown: Unhandled exception at line 8290, column 5 in http://.../scripts/pdf ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Refining the selection choices in the dropdown menu

I am in need of updating multiple Drop-downs automatically by filtering the options from a database for the subsequent Dropdown. The technologies I am using on my website are jQuery, JavaScript, AJAX, and PHP. This feature is quite common on websites that ...

When using VueJs, the input value may not clear upon pressing the ESC key for the first time

When I press the ESC key, my input should clear. However, I am experiencing a bug where the input is not cleared after the first press of the ESC key; it only clears after the second press. Even though the console displays an empty value for the input aft ...

Caution: Make sure to assign an object to a variable before exporting it as the default module

While working with react-redux, my root Reducer appears like this: import Customers from "./customers/reducer"; export default { Customers }; Recently, I encountered a warning saying: Assign object to a variable before exporting as module def ...

What could be the reason my node.js application built with express is unable to retrieve data from mongoose

Currently, I have experience in PHP MVC and recently delved into learning Nodejs. Here is how my app directory structure looks like: root - controllers -user.js - model -user.js - public -stylesh ...

Troubleshooting: Vue.js not triggering method after watching object

I am in need of watching a prop that is an object, so here is my script: <script> export default { watch:{ filter: { handler:(newval)=> { console.log("I have new data",newval) //this works thi ...

Updating a Mongo Record using the ID obtained from another Record's retrievalI hope this meets your needs

One of my current tasks involves creating an API endpoint with specific functionality. The goal is to input an Object ID into the path, locate the record associated with that ID, access a particular field within this object which contains another ObjectID ...

When you invoke a function within Angular 1.5 as a fresh component emerges

I have a component where clicking on a button triggers the invocation of another component. model.alert = function () { modalInstance = $uibModal.open({ template: '<abc-xyz return-value="model" on-cancel="Cancel()">& ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...