How to do an update on Node.js and Mongoose

0
{
    "_id": "58fe27e0e340671c9859c995",
    "__v": 0,
    "form": [
    {
        "_id": "58fe2b1de437791cd02b9a8c",
        "sections": [
            {
                "_id": "58fe2b1de437791cd02b9a8d",
                "input": {
                    "_type": "radio"
                }
            }
        ]
    },
    {
        "_id": "58fe2ca32470711c586d6b6e",
        "sections": []
    }
    ]
}

var save = function(req, res) {
    var survey = {};
    survey.id = req.params.surveyId; // 58fe27e0e340671c9859c995
    survey.form_id = req.params.formId; // 58fe2b1de437791cd02b9a8c
    survey.newObj = req.body.sections; // [{ input: {_type: 'checkbox'}}]

    Survey.update(
        { _id: survey.id }, // 58fe27e0e340671c9859c995 
        {$set:
        {'form': { _id: survey.form_id , sections: survey.newObj } }
        },
        {safe: true, upsert: true},
        function(err, model) {
            if (err)
                res.send(err);
            res.json(model);
        }
    );
};

I'd like to replace what's inside the entire array of objects ( sections ) with a new array of objects: [{ input: {_type: 'checkbox'}}] at _id: 58fe2b1de437791cd02b9a8c

My function save is not working.

    
asked by anonymous 24.04.2017 / 19:04

1 answer

0

Hello, you are trying to update an array (form) inside an array, right?

For this you have to use the positional operator ($). I do not know mongoose or node.js, I can help you in mongoshell: the update would look like this (assuming the collection is "survey"):

db.survey.update({"_id":"58fe27e0e340671c9859c995", "form._id" : "58fe2b1de437791cd02b9a8c"} ,{$set : {"form.$.sections" : [{ input: {_type: 'checkbox'}}]}})

Remembering that the upsert option will not work with the positional operator, the document must exist in the database for the above query to work correctly.

What I saw in the code is just replace the parameters in your method / function.

    
26.04.2017 / 15:51