How to update to Node.js and Mongoose

Asked

Viewed 970 times

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 would like to replace what is inside the object array (sections) whole for a new object array: [{ input: {_type: 'checkbox'}}] in the position of _id: 58fe2b1de437791cd02b9a8c

my Function save is not working.

1 answer

0

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

For this you have to use the positional operator ($). I don’t know Mongoose or Node.js, I can help you with mongoshell: the update would look like this (assuming 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 needs to exist in the bank for the above query to work correctly.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.