Naor Malca
Naor Malca

Reputation: 143

Mongoose And mongodb findById with object in object

i want make a vote app,i have a schema called Poll. in the Poll schema i have a "options" object. i want to update the options.vote by id. how i call to Poll(id).options(id).vote? that my try:

app.post("/:id/:option_id", function(req, res){
    Poll.findById(req.params.id,function(err, poll){
       if(err){
           console.log("Vote(find the Poll) post err");
       } else{
            poll.options.findById(req.params.option_id,function(err,option){
               if(err){
                   console.log("Vote(find the option) post err");
               } else{
               option.vote++;
               option.vote.save(function(err){
                  if(err){
                   console.log("save vote error");
               } else{
                   res.redirect("/:id/:option_id");
               } 
               });
           }});
       }

Upvotes: 0

Views: 152

Answers (1)

Shubham Jain
Shubham Jain

Reputation: 930

You cannot use poll.options.findById as it is mongoose function and poll which you get inside of callback and poll.option is not a Poll schema object. What you may try to do is: I am assuming here that options is an array having a field of Id and one of vote. So you may try as:

var _ = require('lodash');

Poll.findById(req.params.id,function(err, poll){
   if(err){
       console.log("Vote(find the Poll) post err");
   } else{
       var options = poll.options;
       var optionIndex = _.findIndex(options,["id", req.params.option_id])
       poll.options[optionIndex].vote ++;
       poll.save(function(err)){
            if(err){
               console.log("save vote error");
           } else{
               res.redirect("/:id/:option_id");
           } 

       }
   }
});

EDIT: Lodash a simple library that has some array manipulation methods written for usage.

Upvotes: 1

Related Questions