NestJS和Mongoose通过引用对象Id查找

t3irkdon  于 2023-04-21  发布在  Go
关注(0)|答案(3)|浏览(142)

我有一个Mongo的Users集合和一个Addresses集合。每个地址都由一个用户拥有。下面是我的schema类:

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)

然后我有一个AddressService,它可以为用户获取地址:

@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 })
  }
}

此代码有一个错误:Type '_ObjectId' is not assignable to type 'Condition<User>我也试过将userId作为字符串传递,但也不起作用。
使用另一个集合的引用ID查询集合的正确方法是什么?

ddarikpa

ddarikpa1#

我认为user字段的类型不应该是User,尽管NestJS文档是这么说的。它应该是Types.ObjectId类型。
类似这样的东西(以及更清洁的进口):

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)

我从here得到这个。
你也可以告诉TypeScript,这可能是一个字符串,一个ObjectId或一个User,通过声明它:user: string | Types.ObjectId | UserDocument;

kadbb459

kadbb4592#

不确定这是否是正确的方法,但这是我最终解决这个错误的方法:

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

ltskdhd13#

下面的代码可以正常工作:

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

    return record;
}

相关问题