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

138
Views
How to get the first item of an array field I get with populate in mongoose?

I have a mongodb collection and I want to populate a nested field when I return data from the database. I want to return only specific fields, the code below with explain more.

this is my schema

const hallSchema = new Schema({
  hallName: { type: String, required: true },
  email: { type: String, required: true },
  images: [{ type: String, required: true }],
});

and this is code I'm writing to get the first image of the images array 

chatRooms = await ChatRoom.find({ _id: convertedIds })
      .populate("hallId", `hallName ${images[0]}`);

the query above is failing because it is invalid, how can I get the first item of images array? Thanks for any help

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

0

What I understand is that you want to populate data in hallId and from populated hallId data you want to select the first image from the images array. So to project fields from populated data you can do this, It works for me,

const chatRooms = await ChatRoom.find({ _id: convertedIds })
    .populate({ path: 'hallId', select: {
        hallName: 1,
        images: { $slice: ['$images', 1] },
    }
});
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!