Search code examples
typescriptmongodbnestjs

How to apply populate to an array of ObjectId?


I'm trying to make a query from NestJs to a MongoDB database to fetch an object with the following structure:

{  
 "_id": "64b89403e704cb73a2d42140",  
 "programas": [64b075f35742e25803cd2357, 64b075f35742e25803cd2357],
}

I have tried it in the following ways:

  async obtenerInstructores(): Promise<NotFoundException | Instructor[]> {
    const response = await this.instructorModel.find().populate('sede').populate({path: 'programas'}).exec();

And they both return an empty array.

How can it be done?

I hope that when making the request, it returns an array with the data of those documents, not the ObjectId.


Solution

  • Based on the object structure you provided, it seems like you are trying to populate an array of references to other documents in the programas field. To populate the programas field with the actual documents instead of just the ObjectIds, you can use the populate() method with the path option to specify which field to populate and the model option to specify the Model for the referenced documents. Here's an example of how you can modify your query:

    async obtenerInstructores(): Promise<NotFoundException | Instructor[]> {
      const response = await this.instructorModel.find().populate('sede').populate({ path: 'programas', model: 'Programa' }).exec();
      return response;
    }
    

    In this example, 'Programa' is the name of the Model for the referenced documents in the programas field. Replace it with the actual name of your Model.

    This should fetch the documents with the populated programas field containing the actual documents instead of just the ObjectIds.