Not sure whether I am missing something but cant get populating virtuals to show up in object; getter-setter virtuals are fine.
Minimal example:
Schema setup:
userSchema = new mongoose.Schema(
{
_id: String,
firstName: String,
lastName: String,
followingIds: [String],
},
{
toObject: { virtuals: true, getters: true },
toJSON: { virtuals: true, getters: true },
}
).pre("findOne", function () {
this.populate("followedByIds");
});
userSchema.virtual("fullName").get(function () {
if (this.firstName && this.lastName) {
return `${this.firstName} ${this.lastName}`;
}
return this.firstName || this.lastName || undefined;
});
userSchema.virtual("followedByIds", {
type: [String],
ref: "Users",
localField: "_id",
foreignField: "followingIds",
});
mongoose.model("Users", userSchema, "users");
Now if I call user = await this.User.findOne({ _id: some_user_id});, console.log(user.followedByIds) actually has correct values - showing that followedByIds is correctly populated (i.e., containing User objects that follows this particular user). However, if I just console.log(user) then followedByIds field simply does not show up! Moreover, trying to res.status(200).send(user) also won't sent over followedByIds field.
However, fullName field works perfectly. It shows up when I console.log(user) and it can also be sent over to client.
I searched over the internet but found nothing. Please advise. Relevant packages:
"mongoose": "^6.5.2",
"express": "^4.18.1",
"typescript": "^4.7.4"