I have an object like this
==================records=========={ Id: 5114a3c21203e0d811000088,
userId: \'test\',
sUserId: test,
userName: \'test\',
ur
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);
Just use,
var convertedJSON = JSON.parse(JSON.stringify(mongooseReturnedDocument);
and Then,
convertedJSON.newProperty = 'Hello!'
'Hello!' can be anything, a number, a object or JSON Object Literal.
Cheers! :)
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
.
My variant.
If schema defined with {strict:false}
you can simply add new property by
recorcd.newProp = 'newvalue';
If schema defined with {strict:true}
you can either convert Mongoose object to object as mentioned earlier or use command
record.set('newProp','newValue',{strict:false})
See http://mongoosejs.com/docs/api.html#document_Document-schema
You could also use the lean() method, e.g. const users = await Users.find().lean().exec()
From the mongoose documentation:
Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments. They have no save method, getters/setters or other Mongoose magic applied
If you have loaded this object into records
, both records.Name = "test"
or records['Name'] = "test"
will work. You have either not loaded the object correctly, or are inserting an undefined value into it.
To test: add console.log(records.userId)
, this should print 'test' to the terminal.
Also add console.log(name)
. If you get ReferenceError: name is not defined
, you obviously cannot do: records.Name = name