I am building an API which reads a list of users. My mongoose Users model has a virtual field "fullname" which returns a concatenated string containing the first and last names of the user. When I read the database and return the users as JSON from my API, I am unable to see this field in the returned JSON.
It turns out that the JSON stringify removes the virtual fields, even if their "typeof" returns "string"
I found a solution by using an array map function to extract those virtuals into other properties, but I have to clone all the properties to another object in order to make them pass through the stringify. It makes me loop over values which is not efficient. I would prefer a cleaner, documented soltuon
I have been adding the following options to my mongoose schema :
toObject: {
virtuals: true
}
,toJSON: {
virtuals: true
}
It turns out, after logging the whole data, that it does enable virtuals to be outputted when JSON.Stringified . It was also necessary to put the virtuals: true in the toObject option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With