Prats
Prats

Reputation: 1765

Add a new attribute to existing json object in node.js

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

Upvotes: 29

Views: 65614

Answers (7)

venoel
venoel

Reputation: 458

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

Upvotes: 3

Leonardo Dalcin
Leonardo Dalcin

Reputation: 31

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

Upvotes: 3

majorobot
majorobot

Reputation: 142

I experienced a similar problem, and hope that my hours of existential frustration help others in the same situation. My inclination was to believe that documents returned via Mongoose are read-only. This is actually not true.

However, you cannot assign a property to your document that is not also in your Schema.

So, unless your schema has the following:

{
    Name: {String}
}

you will be constantly frustrated by trying to assign Name to your document.

Now, there are workarounds in the answers above that also worked for me, but they do not get to the root of the problem:

myDocument.toObject();
JSON.parse(JSON.stringify(myDocument);

These will work, but in my opinion they just hide the problem. The real issue is that Mongoose is smarter than we realized and is enforcing your schema, as it should.

Upvotes: 6

godimedia
godimedia

Reputation: 999

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! :)

Upvotes: 11

Haywire
Haywire

Reputation: 878

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.

Upvotes: 13

droider
droider

Reputation: 752

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

Upvotes: 56

neelsg
neelsg

Reputation: 4842

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

Upvotes: -1

Related Questions