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

277
Views
How to fill multiple models with mongodb using "population"

I am trying to display all the data with the "populate" statement. But I only get one "populate" but when I put many it doesn't work. what I want to do is to bring me the data from the "User", "Customer" model as well.

This is my code

My Model:

import { model, Schema } from 'mongoose';

const RoomSchema = new Schema({
  Users: [
    {
      agentId: {
        type: Schema.Types.ObjectId,
        ref: "User",
        required: false,
      },
      customerId: {
        type: Schema.Types.ObjectId,
        ref: "Customer",
        required: false,
      },
      typeId: Number, // 1 - agent, 2 - client
    },
  ],
  Messages: [
    {
      agentId: {
        type: Schema.Types.ObjectId,
        ref: "User",
        required: false,
      },
      customerId: {
        type: Schema.Types.ObjectId,
        ref: "Customer",
        required: false,
      },
      message: {
        type: String,
        required: true,
      },
      date: Date,
      sender: Number,
    },
  ],
  FinishAt: Date,
  FinishBy: String,
  typeFinishBy: Number, // 1 - agent, 2 - client
}, {
    timestamps: true,
    versionKey: false
});

export default model('Room', RoomSchema);

this is the sentence I am using

import Room from "../models/Room.js";

async function getOnlyRoom(id) {

 const foundRoom = await Room.findById(id)
 .populate('Users.agentId')
 .populate('Users.customerId')
 .populate('Messages.agentId')
 .populate('Messages.customerId')
 .execPopulate();

  return foundRoom
}

Image of Json Postman

only works with one

foundRoom.populate('Users.customerId')

Works with only populate

this is the error image of error

Thank you very much for your help

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

0

I have found the solution to my problem I was researching the solution on the mongoose website and did it with a single populate.

 const populateRoom = await foundRoom
.populate([
  { path: 'Users.agentId', select: 'name' },
  { path: 'Users.customerId', select: 'name' },
  { path: 'Messages.agentId', select: 'name' },
  { path: 'Messages.customerId', select: 'name' }
])

return populateRoom;
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!