Home > Back-end >  How do I get a virtual in mongoose, If a property is deselected
How do I get a virtual in mongoose, If a property is deselected

Time:09-17

lets say I have post Model and schema contains UserId , Title, Desc and likes array which takes userId's as ref

when I make a query I get a virtual property like this to find out num of like of a post would have

schema.virtual("numLikes").get(function () {
  return this.likes.length;
});

But the problem is when I run the findById() Method I dont want to get likes from database because likes array would contain large list of users

 const post = await Post.findById(postId).select("-likes -shares");

so how do I get Likes count without fetching likes array ?

CodePudding user response:

I believe this can be done using aggregation, by using the $size operators in a projection:

const aggregate = Post.aggregate([
  { $match: {_id: postId}},
  { $project: {
      numberOfLikes: { $size: "$likes" }
    }
  }
]);

https://docs.mongodb.com/manual/reference/operator/aggregation/size/ https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-project

  • Related