What is the best way to implement this code using MongoDB's $push and $inc operators?

Having some trouble getting this code to work properly where I use $inc to increase the number of likes and $push to add the userId to the usersLiked array:

Sauce.updateOne(
    { _id: req.params.id },
    {
      ...sauceObject,
      likes: req.body.like,
      dislikes: req.body.like,
      usersLiked: req.body.userId,
      usersDisliked: req.body.userId,
    }
  )
    .then(() => res.status(200).json({ message: "Sauce liked !" }))
    .catch((error) => res.status(400).json({ error }));

I attempted this approach, but encountered an error:

db.Sauce.update(
        { _id: req.params.id },
        {
          $push: { usersLiked: req.body.userId },
          $inc: { likes: 1 },
        }
          .then(() => res.status(200).json({ message: "Sauce liked !" }))
          .catch((error) => res.status(400).json({ error }))
      );

Your assistance is greatly appreciated :D

Answer №1

Implementing functions in your code is vital for proper functionality, as the code will not work without them. Additionally, consider utilizing async functions to efficiently increase the number of likes.

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

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

Traverse the NSArray of items lacking identifiers in Objective C

My NSArray is structured like this: [{ "Id":"456", "Type":"Dog", "Sound":"Bark", }, { "Id":"789", "Type":"Cat", "Sound":"Meow", }] I attempted the following: for (id key in array) { // This approach did not work NSLog(@"%@", key[@"Ty ...

Issue: [ng:areq] The parameter 'MainController' is not recognized as a function, it is undefined in Internet Explorer (IE)

I find it somewhat challenging to pose this query since there are numerous akin to it, yet I've dedicated 5 hours today attempting to resolve the underlying cause of this predicament. Despite my application functioning flawlessly in Chrome and Firefox ...

Combine and compress an array field within MongoDB

I have a Schema: var ProjectSchema = new Schema({ title: { type: String, default: '' }, categories: [{ type: Schema.ObjectId, ref: 'Category' }], author: { type: Schema.Object ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

Understanding the differences between paths and parameters of routes in express.js

My express application has the following routes: // Get category by id innerRouter.get('/:id', categoriesController.getById) // Get all categories along with their subcategories innerRouter.get('/withSubcategories', categoriesControll ...

Excluding certain images from a JavaScript Photobox animation within a div - a step-by-step guide

Currently, I am using photobox to showcase all the images in a div as part of a beautiful gallery display. However, there is one image that I do not want to be included in this gallery - a PDF icon which, when clicked, should download a PDF file. The issue ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Retrieve a collection of documents matching my search criteria using the Spring framework in conjunction with MongoDB

Here is a glimpse at my Model Class: package io.springBoot.ProductionDetails; import org.springframework.data.annotation.Id; public class ProductionDetailsModel { //Defined entity for ProductDetails @Id private String productId; ...

Manipulating classes with JQuery through click events

$('.toggle-button').on('click', function() { $('body').addClass('changeCursor'); }); $('.toggle-button.toggle-active').on('click', function() { $('body').removeClass('c ...

Populate a Dictionary with Array elements

I'm looking to enhance my dictionary by adding new strings to the items. My approach involves creating a list of strings labeled as item for each key. Below is the current state of my code: Sub AccountEntitlements() Dim sh1 As Worksheet Dim ...

Error ORA-01422 occurs when a retrieval query fetches more rows than were expected, especially when handling a JSON object

I have a scenario where I need to retrieve entries from a table based on a non-unique ID field. After extracting these entries, I aim to insert them into a JSON object for eventual return to JavaScript. Below is the snippet of my current implementation: DE ...

The only React element that is rendered inside a for loop is the last one

I'm struggling with a function that is supposed to render an infinite number of strings as Comment components, but it only displays the last component. This is the function I'm working with: function displayComments(...comments) { for(let i ...

Display a sublist when a list item is clicked

I am receiving a JSON object in my view that looks like this: $scope.mockData = [ { "folder": "folder1", "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }] }, { "folder": "folder2", "reports": [{ "name": ...

Using Jquery to dynamically update input values during key events

I am encountering an issue with a select tag. When I use the keydown event to set a value from the dropdown options as follows: $(this).find("option[value='11']").attr('selected', 'selected') The dropdown is displaying 12 in ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

Error: The variable "context" has not been defined

I am currently facing an issue while trying to develop a sendNotification function using node.js and Firebase function. I am encountering a problem where I am not receiving any notifications from the sender, and upon checking the Firebase function logs, I ...

JavaScript encountered an issue: Uncaught ReferenceError - 'userNumber' is undefined at line 43

I'm currently working on a JavaScript guessing game where I've already set up the necessary functions. However, I keep encountering an error. An error in my JavaScript code is causing a ReferenceError: userNumber is not defined on line 43 to b ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...