How to Update a Nested Document in Mongoose

I am currently working on a polls application using angular, express, and mongoose.

Here is an overview of my data structure:

var mongoose = require('mongoose');

var responseSchema = new mongoose.Schema({
    responseText: String,
    votes: {
        type: Number,
        default: 0
    }
})
module.exports = mongoose.model('Responses', responseSchema);

var pollsSchema = new mongoose.Schema({
    question: String,
    responses: [responseSchema]
})

module.exports = mongoose.model('Polls', pollsSchema);`

Essentially, I have a model for polls which contains a subdocument model for responses.

When a user casts a vote, I aim to increment the vote count for that particular response. Here is the code snippet I am currently working on but encountering issues.

router.post('/api/polls/:id/vote', function (req, res, next) {

    console.log("Poll ID : " + req.params.id);
    console.log("Option ID : " + req.body._id);
    Polls.findOneAndUpdate({
        _id: req.params.id
    }, {

        $inc: {
            'responses.id(req.body.id).votes': 1
        }

    }, function (err, post) {

        if (err) return next(err);
        console.log(err);
        console.log(post);
        console.log(post.responses.id(req.body._id).votes);
    });
})

Update: Revised version

In summary, the request parameters include the Poll ID while the response body includes the response ID. Although I can log the vote value, I am struggling with writing the appropriate query. Any assistance would be greatly appreciated.

Thank you!

Answer №1

If you want to increment a value in MongoDB, you can utilize the $inc operator. For more information, please refer to the official documentation.

To implement this in your code, you can use the following snippet:

Polls.findOneAndUpdate({
        _id: req.params.id,
        responses._id: req.body._id
    }, {
        {$inc: {'responses.$.votes': 1}}
    });

Answer №2

Discovered a solution: The approach of using findOne to narrow down the id, followed by executing the query in the callback might seem unconventional, but it gets the job done. If anyone knows a better method, I'm all ears. Thank you!

router.post('/api/polls/:id/vote', function (req, res, next) {

    Polls.findOne({
        _id: req.params.id
    }, 'responses', function (err, post) {
        post.responses.id(req.body._id).votes++;
        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

JSP checkbox functionality

I have been attempting to solve this issue since last night, but I am struggling and need some help. There are two pages, named name.jsp and roll.jsp. In name.jsp, there are two input text boxes and one checkbox. After entering data in the text boxes and ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now? Previously: { test: /\.js$/, loader: ...

Animating elements with AngularJS: What's the best way to increase the element's width by "+300px" when clicked?

Currently, I am experimenting with animations using ngAnimate in AngularJS. I have a div element and my goal is to make it shift to the right when a button is clicked. In jQuery, achieving this effect is simple, like so : .animate({marginLeft: "+=300"}, ...

Empty the localStorage when terminating the IE process using the Task Manager

Utilizing HTML5 localStorage to keep track of my application session has been a useful feature. Here is a snippet of the code I am currently using: if(typeof(Storage)!=="undefined") { if(sessionStorage.lastname=="Smith") { alert("Your ses ...

Utilizing Nginx to Reverse Proxy to Node.js and Implement Rewrites

I have various applications running in the background behind an Nginx reverse proxy. One of these applications is a Node server using Express.js. I am forwarding domain.com/demo/app/<path> to localhost:7003/<path> through this Nginx configurati ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

What is the procedure for re-executing the request handler in a Node.js and Express application?

Currently, my setup involves node, express, and mongojs. Here is a code snippet that exemplifies my configuration: function mongoCallback(req, res) { "use strict"; return function (err, o) { if (err) { res.send(500, err.message); } else ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Utilizing the require function to implement an AngularJS Controller without having

I've been working with requireJS in my application. Every time I try to register a controller on my module, it gives me an error saying that the controller is not defined. Here's the code for my LoginController located in login.controller.js: f ...

Issue with Firefox mobile's camera functionality

I am facing an issue with my web app for mobile devices where I am trying to display the mobile camera using Firefox mobile browser. I am using nodejs with express as a server and connecting to the server via localhost with my smartphone. Although Firefox ...

What is the best way to add data-content to hr:after using JavaScript?

Adding style to an element in javascript can be simple. For example: myElement.style.color = "red"; However, what if I wanted to achieve something like this: hr:after { content: "myRuntimeValue" } Is there a way to do this using javascript? ...

Enhance the existing User model in loopback by adding additional properties and functionalities

In my loopback app, I am looking to create a model that represents a user profile. However, the default User model provided by loopback only includes the properties: username password realm emailVerified I am wondering what is the most effective approac ...

Encountering a 500 POST error (Server Internal Error) with the message: "Error: data and hash arguments required" while submitting the sign-in form to the server

Currently, I am developing my first ecommerce project using the MERN stack. However, I have encountered a roadblock while attempting to submit the login data to the server after clicking on the submit button. The issue seems to be related to bcrypt.compare ...

The functionality to display dynamic images in Vue.js appears to be malfunctioning

As a newcomer to vue.js, I am facing a challenge in dynamically displaying images. Manually changing the images works fine, but I'm running into issues with dynamic display. I've come across similar problems online, but none of the solutions seem ...

Vue.js SyntaxError: Identifier came out of nowhere

An error was reported by VUE debug mode in this line of my code: :style="{transform : 'translate3d(' + translateX + 'px,0, 0)'}"\ The documentation does not provide instructions on how to include a variable within a style binding ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Nest a Div inside another Div with a precise margin of 10 pixels

Recently, I attempted to create a fullscreen webpage like this one: My goal was to have the color of each element change randomly every second. Here is the JavaScript code I implemented: <script> var tid = setInterval(chngColor, 1000); ...

Issue with receiving output from tessearct.js in PDF format

I am currently working on a basic javaScript OCR (Optical Character Recognition) application using tesseract.js. I have included {tess_create_pdf: "1"} in the .recognize() method to receive the result in PDF format, but it seems to be malfunctioning. Can ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...