Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
Asim Zaidi Avatar asked Jun 16 '15 23:06

Asim Zaidi


2 Answers

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);

});
like image 87
dting Avatar answered Sep 23 '22 07:09

dting


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' }

like image 34
Jose Mato Avatar answered Sep 23 '22 07:09

Jose Mato