Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom field during find in Mongoose

So I have next model:

const PostSchema = new Schema({
    name: String,
    likedBy: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
})

I also have middleware called isLoggedInOrNot, which populates req.user if there is authorization.

So on index page, I want to find and return newest posts, and each one should have a custom field added didILiked. So what I want is something like this:

Post.find().select({ didILiked: { likedBy: req.user._id } }).sort('-createdAt').exec()

I know the above is not even valid, but just a demonstration of what I would like to accomplish.

So let's say didILiked gets created (like virtual field, not stored in db), and it should be true/false or null if req.user is undefined.

Is there a way to accomplish this?

like image 815
Wolfdog Avatar asked Oct 19 '25 14:10

Wolfdog


1 Answers

You have to use aggregation here. Something like

Post.aggregate([
  { "$addFields": {
    "didILiked": { "$in": [mongoose.Types.ObjectId(req.user._id), "$likedBy"] }
  }}
])
like image 104
Ashh Avatar answered Oct 22 '25 03:10

Ashh



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!