Wednesday, 19 April 2017

Mongoose array update not working

I have the following document in my collection :

{
    "_id": {
        "$oid": "58e47622968feb182c4a26b5"
    },
    "pollOptions": [
        {
            "vote": 0,
            "option": "blue"
        },
        {
            "vote": 0,
            "option": "green"
        },
        {
            "vote": 0,
            "option": "red"
        }
    ],
    "polltitle": "what is your favorite color?",
    "user": {
        "username": "mike",
        "email": "mike@email.com",
        "password": "abc",
        "passwordconf": "abc"
    },
    "__v": 0
}

I want to update the vote number based on the user's choice. I could update just the vote number (couldn't get that to work), so I'm trying to update the whole pollOptions array.

Here is below what I did (2 different approaches). I have the pollData array right, with the 3 objects, as in the document above. The query returns the right object as in the document above. However, this does not update the pollOptions array in the DB. Don't understand why this is not working.

app.post('/api/poll/:userId/:polltitle/:vote', (req, res) => {
    let pollData = req.body;
    let userId = req.params.userId;
    let polltitle = req.params.polltitle;
    let query = { 'user.username': userId, 'polltitle': polltitle };
    myModel.findOne(query, (err, doc) => {
        doc.pollOptions = pollData;
        doc.save();
    });
})

The following does not work either.

app.post('/api/poll/:userId/:polltitle/:vote', (req, res) => {
    let pollData = req.body;
    let userId = req.params.userId;
    let polltitle = req.params.polltitle;
    let query = { 'user.username': userId, 'polltitle': polltitle };
    let update = { $set: { 'pollOptions':  pollData } };
    myModel.findOneAndUpdate(query, update, (err, doc) => {
        res.send(doc);
    });
});

Thanks in advance for your kind help !



via John Doe

No comments:

Post a Comment