Missing attributes in your HTTP response with Express.js and Mongoose ORM
The function I wanted to implement:
- Get the model object from the db
- Set new fields “fieldA” and “fieldB” on the model object
- Write model to http response
async (req, res) => {
let model = findModelById(id);
model.fieldA = valueA;
model.fieldB = valueB;
res.send(model);
}
Surprisingly, the response did not have these fields set!
I started debugging and I figured that when the JSON response is generated, eventually toObject() method of Mongoose’s Document object is executed, which ignores all the fields associated to the model object that are not part of the schema.
If you are facing a similar issue, the trick is to get a plain js object using toObject() and set the fields on this object.
async (req, res) => {
let dbModel = findModelById(id);
let model = dbModel.toObject();
model.fieldA = valueA;
model.fieldB = valueB;
res.send(model);
}