'unable to add property to the json object

I am trying to add status to a response on successful update but I am not able to add the status property to json object of form. Here is my code

apiRouter.post('/forms/update', function(req, res){

    if(req.body.id !== 'undefined' && req.body.id){

        var condition = {'_id':req.body.id};

        Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){

            if (err) return res.send(500, { error: err });

            var objForm = form;

            objForm.status = "saved successfully";

            return res.send(objForm);

        });

    }else{
        res.send("Requires form id");
    }

});

and here is the response that I get, notice status is missing

{
    "_id": "5580ab2045d6866f0e95da5f",
    "test": "myname",
    "data": "{\"name\":3321112,\"sdfsd\"344}",
    "__v": 0,
    "id": "5580ab2045d6866f0e95da5f"
}

I am not sure what I am missing.



Solution 1:[1]

Try to .toObject() the form:

Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){

    if (err) return res.send(500, { error: err });

    var objForm = form.toObject();

    objForm.status = "saved successfully";

    return res.send(objForm);

});

Solution 2:[2]

Mongoose query result are not extensible (object are frozen or sealed), so you can't add more properties. To avoid that, you need to create a copy of the object and manipulate it:

var objectForm = Object.create(form);
objectForm.status = 'ok';

Update: My answer is old and worked fine, but i will put the same using ES6 syntax

const objectForm = Object.create({}, form, { status: 'ok' });

Another way using spread operator:

const objectForm = { ...form, status: 'ok' }

Solution 3:[3]

Try changing res.send(objForm) to res.send(JSON.stringify(objForm)). My suspicion is that the the Mongoose model has a custom toJson function so that when you are returning it, it is transforming the response in some way.

Hopefully the above helps.

Solution 4:[4]

Create empty object and add all properties to it:

const data = {};
data._id = yourObject._id; // etc
data.status = "whatever";
return res.send(data);

Solution 5:[5]

Just create a container.

array = {};
Model.findOneAndUpdate(condition, function(err, docs){
    array = docs;
    array[0].someField ="Other";
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dting
Solution 2
Solution 3 deanmcpherson
Solution 4 TomoMiha
Solution 5 Samuel