NestJS Mongoose populate() Not Working for Arrays of ObjectIds, But Works for Single ObjectId

I am developing an application using NestJS and Mongoose and have encountered a problem when using the populate() method in a schema that contains an array of ObjectIds. The method works correctly when the field is a single ObjectId, but fails to populate properly when the field is an array of ObjectIds.

Models and Schemas

Here are the Mongoose schemas for User and Card:

User Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types, Document } from 'mongoose';

@Schema()
export class UserClass {
  @Prop({ required: true, unique: true })
  username: string;

  @Prop({ type: [{ type: Types.ObjectId, ref: 'Card' }] })
  cards: Types.ObjectId[];
}

export const UserEntity = SchemaFactory.createForClass(UserClass);
Card Schema

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

@Schema()
export class CardClass {
  @Prop({ required: true, unique: true })
  token: string;

  // Additional properties
}

export const CardEntity = SchemaFactory.createForClass(CardClass);

Repository Method
Here is the method in my repository where I attempt to use populate():


import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from './user.entity';

@Injectable()
export class UsersRepository {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async findUserWithCardsById(userId: string): Promise<UserDocument | null> {
    return this.userModel
      .findOne({ _id: userId })
      .populate('cards')
      .exec();
  }
}

Issue:
When executing the findUserWithCardsById method, the cards field should be populated with the Card documents corresponding to the IDs stored in the user’s cards array. However, the array returns unpopulated, although it does work when the cards field is a single ObjectId (non-array).

Additional Context
Interestingly, when I modify the cards field in the User schema from an array to a single ObjectId:


@Prop({ type: Types.ObjectId, ref: 'Card' })
cards: Types.ObjectId;

The populate() function works perfectly, returning the expected Card attributes. This confirms that the collections and models are correctly connected and referenced, as the population performs correctly when cards is configured as a single ObjectId. This indicates that the issue is specific to handling arrays of ObjectIds.

Question
How can I resolve this issue so that populate() functions correctly with arrays of ObjectIds in NestJS with Mongoose? Is there any additional configuration or step I need to implement to handle arrays of references properly?

Acknowledgements
I would appreciate any help or guidance on how to solve this issue, as it is crucial for the functionality of my application.

Expected Behavior
When using Mongoose’s populate() method with an array of ObjectIds in the User schema, I expect that each ObjectId in the cards array should be populated with the corresponding Card document from the database. This should result in the cards array in the User document containing full Card document details for each reference, not just the ObjectIds.

Here is the code snippet of what I expect to happen:


// Repository method expected to populate user's cards
async findUserWithCardsById(userId: string): Promise<UserDocument | null> {
    return this.userModel
      .findOne({ _id: userId })
      .populate({
        path: 'cards',
        select: 'token subtoken franchise lastDigits validUntil'  // Expected fields to be populated from Card
      })
      .exec();
}

// Expected result structure
{
  _id: userId,
  username: 'johndoe',
  cards: [
    {
      _id: cardId,
      token: 'someToken',
      subtoken: 'someSubtoken',
      franchise: 'someFranchise',
      lastDigits: '1234',
      validUntil: '12/2030'
    },
    // Additional cards populated similarly
  ]
}

This structured result is what I aim to achieve, where each card’s detailed information is retrieved and shown as part of the user’s document. This functionality works as expected when cards is a single ObjectId but not when it is an array of ObjectIds, despite the collections and models being correctly connected and referenced.

New contributor

Alex Piczenik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật