I have an object like this
==================records=========={ Id: 5114a3c21203e0d811000088, userId: 'test', sUserId: test, userName: 'test', url: 'test', Title: 'test' }
I need to add a new field Name : 'test' to the above record, I tried giving records.Name = name, it didn't work.
Helps please
Thanks, Prats
Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .
To add a new key value pair in existing JSON object using JavaScript, we can parse the JSON string with JSON. parse , then add the key-value pairs we want, and then convert the object back to a JSON string with JSON. stringify .
To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.
I am assuming you are trying to add a property to a returned Mongoose Document to reuse it somewhere else. Documents returned by Mongoose are not JSON objects directly, you'll need to convert them to an object to add properties to them. The following should work:
//... record is a mongoose Document var r = record.toObject(); r.Name = 'test'; console.log("Record ",r);
Those finding this problem, OP mentioned in a comment below the original question that the solution for this problem is:
records.set('Name', 'test')
This adds a new attribute called Name
having value test
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With