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.
NewPoll.findById(id, function(poll) {
var option = poll.options.id(/* option id here */);
option.count++;
poll.save(function() {
// yay poll updated
});
})
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
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 ????
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 ???
var thisId = info.options;
var option = poll.options.id(thisId);
//this fails even though console.log shows right id
var thisId = info.options;
var option = poll.options.id('597a0716835fa81004af05b1');
//this works ... not understanding yet why top fails and this passes
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