Wolfdog
Wolfdog

Reputation: 587

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?

Upvotes: 4

Views: 3983

Answers (1)

Ashh
Ashh

Reputation: 46491

You have to use aggregation here. Something like

Post.aggregate([
  { "$addFields": {
    "didILiked": { "$in": [mongoose.Types.ObjectId(req.user._id), "$likedBy"] }
  }}
])

Upvotes: 4

Related Questions