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

后端 未结 7 1763
梦如初夏
梦如初夏 2021-01-17 07:16

I have an object like this

==================records=========={ Id: 5114a3c21203e0d811000088,
  userId: \'test\',
  sUserId: test,
  userName: \'test\',
  ur         


        
相关标签:
7条回答
  • 2021-01-17 07:58

    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);
    
    0 讨论(0)
  • 2021-01-17 07:58

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

    0 讨论(0)
  • 2021-01-17 07:59

    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.

    0 讨论(0)
  • 2021-01-17 07:59

    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

    0 讨论(0)
  • 2021-01-17 08:00

    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

    0 讨论(0)
  • 2021-01-17 08:01

    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

    0 讨论(0)
提交回复
热议问题