'NestJS and Mongoose find by reference object Id

I have a Mongo collection of Users and a collection of Addresses. Each address is owned by one user.Here are my schema classes:


export type UserDocument = User & mongoose.Document
@Schema({ timestamps: true })
export class User {
  // @Prop({ type: mongoose.Types.ObjectId })
  _id: string

  @Prop({ required: true })
  name: string

  @Prop({ required: true, unique: true })
  email: string

  @Prop({ select: false })
  password: string

}
export const UserSchema = SchemaFactory.createForClass(User)

export type AddressDocument = Address & Document
@Schema({ timestamps: true })
export class Address {
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
  user: User

  @Prop()
  line1: string

  @Prop()
  line2?: string

  @Prop()
  city: string

  @Prop()
  state?: string

  @Prop()
  country: string
}

export const AddressSchema = SchemaFactory.createForClass(Address)

Then I have an AddressService that can fetch addresses for a user:

@Injectable()
export class AddressService {
  constructor(@InjectModel(Address.name) private addressModel: Model<AddressDocument>) {}

  async save(address: AddressDto): Promise<Address> {
    const model = await this.addressModel.create(address)
    return model.save()
  }

  async findAddressForUser(userId: string) {
    const userObjectId = new mongoose.Types.ObjectId(userId)
    const users = await this.addressModel.find({ user: userObjectId })
  }
}

This code has an error: Type '_ObjectId' is not assignable to type 'Condition<User> I tried passing the userId as a string as well, that did not work either.

What is the right way to query a collection using a reference Id from another collection?



Solution 1:[1]

I think the user field shouldn't be of type User, despite what the NestJS docs say. It should be of type Types.ObjectId.

Something like this (with cleaner imports aswell):

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

export type AddressDocument = Address & Document
@Schema({ timestamps: true })
export class Address {
  @Prop({ type: SchemaTypes.ObjectId, ref: User.name })
  user: Types.ObjectId;

  ...

}
export const UserSchema = SchemaFactory.createForClass(User)

I got this from here.

You could also tell TypeScript that this may be either a string, an ObjectId or a User by declaring it as: user: string | Types.ObjectId | UserDocument;

Solution 2:[2]

Not sure if this is the proper way of doing this but this is what I ended up doing to get around that error:

  async findAddressForUser(userId: string): Promise<Address[]> {
    const query: any = { user: new mongoose.Types.ObjectId(userId) }
    return await this.addressModel.find(query).exec()
  }

Solution 3:[3]

The following code worked:

async findModulesUser(id: string) {
    const record = await this.modulesuserModel
      .find({ user: new Types.ObjectId(id) })
      .populate("user", ["name", "email"])
      .exec();

    return record;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Inn0vative1
Solution 3 Oleg Valter is with Ukraine