Failed to add property to json object

I am trying to add status to a successful update message, but I cannot add the status property to the form json object. 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 receive, there is no status notification

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

I'm not sure what I am missing.

+6
source share
5 answers

Try the .toObject() 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); }); 
+9
source

The Mongoose query result does not expand (the object is frozen or sealed), so you cannot add additional properties. To avoid this, you need to create a copy of the object and process it:

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

Update: my answer is old and working fine, but I will use it with ES6 syntax

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

Another way to use the spread operator:

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

+6
source

Try changing res.send(objForm) to res.send(JSON.stringify(objForm)) . My suspicion is that the Mongoose model has a custom Json function, so when you return it, it somehow converts the response.

Hope this helps.

0
source

Create an empty object and add all the properties to it:

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

Just create a container.

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

Source: https://habr.com/ru/post/989254/


All Articles