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

The syntax for an AngularJS controller using the "as" keyword

Incorporating AngularJS 1.6.9 with AngularJS Material has been a challenge for me. I am attempting to integrate a menu item feature following the basic usage, but unfortunately, it did not work as expected due to structural differences. After reviewing th ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

Eliminate any unauthorized characters from the email address

My goal is to assist users in avoiding entering invalid characters in an email input field (prior to server-side validation and cleanup). Please note: I am not validating emails on the frontend, only cleaning them up. // Coffeescript $(Element).find(&apo ...

Over time, MongoDB automatically updates boolean values to false

Below is the basic structure of my schema: When I update the value of any of the "powerups" (first 4 items), I set the powerupTimer to the time when that field was changed. Only one powerup can be active at a time, and I want all values to reset to false ...

What is the process for integrating Firebase into $asyncValidators?

I am looking to implement a feature in my Firebase app that ensures usernames are unique. I want the user to be promptly informed if a username is already taken or not. I have been exploring AngularJS's ngModel as it offers an asyncValidator in its co ...

Is the each() method in jQuery essentially a for loop?

Experimenting with adding a serialized class to a group of objects, I attempted the following approach: jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="&apos ...

What is the best way to utilize query parameters without using ui-router?

In my Angular application using ui-router, I am looking to maintain a separate state that is not related to routing. For example, if the URL is #/profile?color=green, the state is "profile" and the app color should be green. If the URL changes to #/profil ...

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

React.js router - struggles to clean up unsightly query parameters in the URL

I've been trying to eliminate the query string by following this solution: var { Router, Route, IndexRoute, IndexLink, Link } = ReactRouter; var createHashHistory = History.createHashHistory; var history = createHashHistory({queryKey: false} ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

There was an error message saying "Unable to locate property 'getElementById' in undefined"

I am facing an issue with a jQuery filter function, and the error message it's showing is: Cannot read property 'getElementById' of undefined function CheckFilter() { var input, filter, table, tr, td, i, searchFilter; input = ...

Complete the request handling in express.js

In situations where I have a straightforward function handling the request, I typically use res.end() and return to terminate it at any point (such as when an error occurs or incorrect data is received). get('/', function (req, res) { if (!r ...

Unable to utilize curl to access the resource in the tut-spring-security-and-angular-js "pairs-oauth2" example

Recently, I followed the instructional guide for creating a secure single page application using both Spring Security and Angular JS. After downloading the source code from GITHUB, I attempted to mimic an external application accessing the "resource" api t ...

What is the process for turning off express logs on my node.js command line interface?

Recently, I've begun delving into the world of node.js and in an effort to improve my debugging practices, I've decided to move away from relying solely on console.log. Instead, I am exploring the use of debug("test message") for my debugging ...

What is the best way to retrieve an element that has been altered in its state?

I encountered a scenario where I want an image to have a border when clicked, and if clicked again, the border should be removed. However, the border should also be removed if another image is clicked instead. I believe there are a couple of approaches to ...

What are some common issues that may cause the template Element directive to not function properly when used with Expressions

Working with angularjs+rickshaw has been an interesting experience. I recently created a simple example inspired by the UFO sightings visualization showcased on Angularjs+Rickshaw. The result was a similar UFO sightings chart. <h3>UFO sightings in 2 ...

What is the proper way to use an AND operation in jQuery on multiple attributes?

I have a list of DIV tags structured as follows: <div status="1" searchText="some text">...</div> <div status="2" searchText="more text">...</div> <div status="1" searchText="even">...</div> To toggle the visibility of ...

Developing an Angular Chart with AJAX

Utilizing the power of angular-chart.js, I have successfully generated a chart with the provided code snippet. However, my goal is to dynamically generate a chart using AJAX calls. Unfortunately, when I attempt to load the chart through AJAX, it fails to r ...

NodeJS Google Cloud Trace for packaged applications

My server-side rendered web application had no issues sending tracing information to Google using express and @google-cloud/trace-agent. However, after bundling our application, all trace information disappeared. While we can still see the requests in the ...