@JohnL3 (John L3) posted a new topic, subject "Help with moongoose findByIdAndUpdate". It read:

   This is what i got to work to update count when someone votes … options is an array … i had to remove a id field in each before i call this eg “_id” : ObjectId(“597a0716835fa81004af05b3”), as it would fail on the text ObjectId part …  
    But i feeling sure there must be a better way than this to update an array in a schema but cant figure out how to do it  
    the id is for the actual schema with all fields you can see it beneath … also this is sent like this to see if it works  
    any help on this would be appreciated.
    [code] 
        NewPoll.findByIdAndUpdate(_id, {
        									"options":[
        									                {
                                "title" : "Html",
                                
                                "count" : 0
                        },
                        {
                                "title" : "Css",
                                
                                "count" : 0
                        },
                        {
                                "title" : "javascript",
                                
                                "count" : 2
                        }
        									]
        									},{new:true}, function(err,poll){
        		if(err) res.json({message: err.message});
        		res.send(poll);
        	})```
        
        This is how it looks in the database 
        
        ```{
                "_id" : ObjectId("597682ad5fbec0275005227a"),
                "username" : "ems_1",
                "pollname" : "Least Favorite",
                "votes" : 1,
                "options" : [
                        {
                                "title" : "Html",
                                "_id" : ObjectId("597a0716835fa81004af05b3"),
                                "count" : 0
                        },
                        {
                                "title" : "Css",
                                "_id" : ObjectId("597a0716835fa81004af05b2"),
                                "count" : 0
                        },
                        {
                                "title" : "javascript",
                                "_id" : ObjectId("597a0716835fa81004af05b1"),
                                "count" : 2
                        }
                ],
                "__v" : 0
        }```
    [/code]

After which, @prohorova (Prohorova) added

    [code]
        NewPoll.findById(id, function(poll) {
        var option = poll.options.id(/* option id here */);
        option.count++;
        poll.save(function() {
        // yay poll updated
        });
        })
    [/code]

To which @JohnL3 (John L3) replied

    Unfortunately this does not work for me … first off i was getting nothing from the function(poll) part … i console.log and was getting null  
    so i changed to function(err,poll)  
    and got my poll but then it errs on option.count  
    i put console.log('in findBy) and then console.log(poll) … so im getting the poll but its failing on options.count ++  
    changed var option = poll.options.id(_id); to **var option = poll.options[2]**  
    it then works … but now i have to rely on finding the array index … but will see if thats going to be a problem ty ty
    [code] 
        in findBy
        { _id: 597682ad5fbec0275005227a,
          username: 'ems_1',
          pollname: 'Least Favorite',
          __v: 0,
          votes: 1,
          options:
           [ { title: 'Html', _id: 597a0716835fa81004af05b3, count: 0 },
             { title: 'Css', _id: 597a0716835fa81004af05b2, count: 0 },
             { title: 'javascript', _id: 597a0716835fa81004af05b1, count: 2 } ] }
        events.js:182
              throw er; // Unhandled 'error' event
              ^
        
        TypeError: Cannot read property 'count' of null ```
    [/code]

After which, @prohorova (Prohorova) added

    Did you just copy pasted code??? You need to pass actual option id into poll.options.id(…)

To which @JohnL3 (John L3) replied

    yep put id in but it dosent accept them had to drop id part and use array index

Then @lfaudreejr (Larry Faudree Jr) said

    Try using $inc:{count: 1} to increment by 1

@JohnL3 (John L3) replied

    [code]
        NewPoll.findById(id, function(err,poll) {  // added err here as without it console.log(poll) was null
        	if(err) res.json({message: err.message});
        	console.log('in findBy')
        	console.log(poll);
        var option = poll.options[2]//.id( _id); //changed poll.options.id(_id) as console.log('Here '+ option) came back as null
        console.log('Here ' +option); // with poll.options[2] i got the poll options
        option.count++; // and with poll.options[2] this worked
        poll.save(function(err,poll) {
        		if(err) res.json({message: err.message});
        		res.send(poll);
        });
        }) ```
        Still wondering is this how others did it would be handier if poll.options.id(_id) worked ...
        hmm red text ????
    [/code]

So @prohorova (Prohorova) replied

    You're probably sending wrong id to poll.options.id

Then @JohnL3 (John L3) said

    No passing in right Id … tried again and found something eg if i pass id in as a paramater it returns null and fails but if i hard code id in it passes ???
    [code] 
        var thisId = info.options;
        var option = poll.options.id(thisId);
        //this fails even though console.log shows right id
        
    [/code]
    [code] 
        var thisId = info.options;
        var option = poll.options.id('597a0716835fa81004af05b1');
        //this works ... not understanding yet why top fails and this passes
        
    [/code]
    
    quick edit id is 24chars in length but when passed as param thisId its 25 chars in length … just have to remove this extra char … will go sort that out hopefully and then it should work  
    edit did a trim and now works … now to find why extra blank space being added

@ilenia (Ilenia) replied

    


{'source': 'discourse', 'url': 'https://forum.freecodecamp.org/t/help-with-moongoose-findbyidandupdate/138647', 'title': 'Help with moongoose findByIdAndUpdate', 'views': 1905, 'has_accepted_answer': True, 'word_count': 636, 'like_count': 1, 'reply_count': 4, 'participant_count': 3, 'posts': 10, 'tags': '', 'author': '@JohnL3 (John L3)', 'participants': '@JohnL3 (John L3), @prohorova (Prohorova), @lfaudreejr (Larry Faudree Jr), @ilenia (Ilenia)', 'image_url': [None], 'created_at': '2017-07-27T19:47:41.935Z', 'last_posted_at': '2021-01-17T09:36:54.913Z'}