Populating multiple fields with a pre "find" middleware
See original GitHub issueHello,
I am trying to specify the fields that should always be populated for the user document in a pre “find” middleware, like this:
userSchema.pre(/^find/, function (next) { this.populate("followers following"); next(); });
But when I send the request it’s just stuck not sending any response.
It works just fine when I only populate one field, either ‘followers’ or ‘following’, but together it won’t work. I tried a bunch of different ways, but nothing seems to work.
I’ve also created a stack overflow question and none of the ideas work. In the mongoose documentation there is only an example of one field being populated, and populating multiple fields really shouldn’t be harder than it is with a normal query populate method, but it is.
If there is really no way to populate multiple fields, this is a huge issue to be fair.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
The issue is that your
populate()
call triggers infinite recursion:this.populate('followers following')
triggers the same middleware for bothfollowers
andfollowing
.As a workaround, add a
_recursed
option so your middleware knows to avoid populating recursively:Nope… The request just gets stuck, and I don’t get a response…
When I do just
this.populate('followers')
or justthis.populate('following')
, they both work fine alone, but if I try to populate both fields it just doesn’t work, I’ve tried a bunch of things…It does work when you do it on the model query, but we should definitely be able to do it in the middleware as well…
I really hope I’m making a mistake somewhere, but I think that unfortunately that’s not the case and that this is a bug…