【问题标题】:NestJS and Mongoose find by reference object IdNestJS 和 Mongoose 通过引用对象 Id 查找
【发布时间】:2021-05-29 09:08:31
【问题描述】:

我有一个 Mongo 用户集合和一个地址集合。每个地址归一个用户所有。这是我的架构类:


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&lt;User&gt; 我也尝试将 userId 作为字符串传递,但也没有用。

使用来自另一个集合的引用 ID 查询集合的正确方法是什么?

【问题讨论】:

  • 你有没有找到正确的方法来使用道具模型和猫鼬通过引用找到数据。如果可以,请分享。我很难找到它。
  • @YerfA42 检查我添加的答案。这行得通。

标签: typescript mongoose nestjs


【解决方案1】:

Inn0vative 你太棒了,谢谢!,这个代码字

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

return record;

}`

【讨论】:

    【解决方案2】:

    我认为 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 那里得到的。

    您还可以通过将其声明为:user: string | Types.ObjectId | UserDocument;

    来告诉 TypeScript 这可能是字符串、ObjectId 或用户

    【讨论】:

    • 这对我有帮助。非常感谢您分享您的解决方案
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-11
      • 2020-03-27
      • 2021-09-24
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多