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

后端 未结 7 1764
梦如初夏
梦如初夏 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 08:20

    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.

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