Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Unable to retrieve virtual fields in express route

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

like image 771
Rayjax Avatar asked Nov 25 '25 16:11

Rayjax


1 Answers

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.

like image 150
Rayjax Avatar answered Nov 27 '25 06:11

Rayjax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!