【问题标题】:How to define mongoose schema ref fields with typescript?如何使用打字稿定义猫鼬模式参考字段?
【发布时间】:2022-01-08 18:37:22
【问题描述】:

我使用以下代码进行架构定义:

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

@Schema({ collection: 'templates' })
export class Template {
    @Prop({
        type: SchemaTypes.ObjectId,
        ref: User.id,
        required: true,
    })
    public user: Types.ObjectId;

    // other fields...
}

我希望在填充模板实体时有用户字段(用户:用户 => 用户名),但我有类型限制:

“ObjectId”类型上不存在属性“名称”

【问题讨论】:

    标签: typescript mongodb mongoose nestjs mongoose-schema


    【解决方案1】:

    在 typescript (nest-js) 中,我使用 virtuals 来代替:

    Schema.virtual('YOUR_VIRTUAL_NAME', {
      ref: 'User',
      localField: 'userOnlyReservableId',
      foreignField: '_id',
      justOne: true,
    });
    

    记得添加架构:

    @Schema({ toJSON: { virtuals: true }, toObject: { virtuals: true } })
    

    在 find 之后最后填充虚拟:

    model.find({}).populate('YOUR_VIRTUAL_NAME')
    

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 2016-04-01
      • 2017-01-20
      • 2018-10-09
      • 2013-01-25
      相关资源
      最近更新 更多