Missing attributes in your HTTP response - Express.js and Mongoose ORM

The function I was implementing:

  • Get the model object from the db using Id
  • Set new fields “fieldA” and “fieldB” on the model object
  • Write document to http response

The code:

async (req, res) => {
    let model = findModelById(id);
    model.fieldA = valueA;
    model.fieldB = valueB;
    res.send(model);
}

Surprisingly, the response did not contain the newly added fields!

As someone who has recently started writing production code using Express and Mongoose ORM, it was difficult to understand what was happening.

So, I started debugging and here is what I found:

When the JSON response is generated, eventually toObject() method of Mongoose’s Document object is invoked. This method ignores all the fields associated to the model object that are not part of the schema that was defined.

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

Hope this helps.

No Comments Yet