I want to add some data into a mongoose model before we return it to front-end, what should I do?
If we want to perform a mongoose query with
Book
and try added other data (e.g book comments) into the query result, the comments would not return to front-end as desired.
It seems the comments are ignored when return to front-end. Is the reason that there is no matched field named comments
in Book model? I've noticed that sometimes we extract the data we want to return from a model instead of directly return the model. Or add some command when perform query using a '-'
in front of a field we do not want to select: select('-_id -oneFieldNameThatYouDoNotWantToSelect')
.
Then, I try to convert mongoose document model into an plain object by using model method .toObject()
, and add other data as new property to this object.
Mongoose Models
, which inherit from Documents
.
In some cases, we could use embedded document or reference document. The above discussion is just a found.
Reference