Alex Piczenik
Alex Piczenik

Reputation: 1

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.

Upvotes: 0

Views: 233

Answers (2)

Serdar
Serdar

Reputation: 53

I know it's a bit late reply, but try the code below.

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: [Types.ObjectId], ref: 'Card' }) // <-- change this 
  cards: Types.ObjectId[];
}

export const UserEntity = SchemaFactory.createForClass(UserClass);

Upvotes: 1

jkaos92
jkaos92

Reputation: 73

The ref option is what tells Mongoose which model to use during population.

In your case, your ref is Card:

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

While your model name is probably CardClass or whatever you use elsewhere in the imports of the module.

You can rename the ref from Card to the name you have registered, which i assume is CardClass, or decide to register a different name in the module, while still using CardClass as the model name (which should also work). Basically this:

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: 'Card', schema: CardEntity }, 
      //...
    ]),
  ],
  controllers: [], // your controllers
  providers: [], // your providers
})
export class AnyModule {}

Upvotes: 0

Related Questions