Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
How do I get a virtual in mongoose, If a property is deselected

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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!