【问题标题】:NestJS - Embedding Nested Document with enum using mongooseNestJS - 使用 mongoose 使用枚举嵌入嵌套文档
【发布时间】:2018-11-09 14:10:44
【问题描述】:

我正在尝试创建一个这样的架构结构,

import  *  as  mongoose  from  'mongoose';
import  *  as  Stop  from  'stop-model';
    export  const  RouteSchema  =  new  mongoose.Schema({
    _id:  String,
    stop: [Stop],
    type: { type:  String, enum: ['INBOUND', 'OUTBOUND'] }
    }, {
    versionKey:  false,
    timestamps: { createdAt:  'createTime', updatedAt:  'updateTime' }
});

停止模型是一个接口,

import { Document } from  'mongoose';
export  interface  Stop  extends  Document {
    _id:  String,
    stopName:  String,
    type:  StopType,
    createTime:  number,
    updateTime:  number
}

export  enum  StopType {
    PARKING=  'PARKING',
    WAYPOINT  =  'WAYPOINT',
    STOP  =  'STOP'
}

但是运行时出现以下错误

TypeError: Undefined type PARKING at StopType.PARKING 你有没有 尝试嵌套模式?您只能使用 refs 或数组进行嵌套。

我的目标是在Routes 集合中列出Stops

我也有一个像这样定义的StopSchema

import  *  as  mongoose  from  'mongoose';

export  const  StopSchema  =  new  mongoose.Schema({
    _id:  String,
    stopName:  String,
    type: { type:  String, enum: ['PARKING', 'WAYPOINT', 'STOP'] }
    }, {
    versionKey:  false,
    timestamps: { createdAt:  'createTime', updatedAt:  'updateTime' }
});

我不确定如何在RouteSchema 中使用StopSchema 作为参考。 (在这个答案Referencing another schema in Mongoose 的行中,但是以 NestJS 的方式)。

【问题讨论】:

    标签: mongodb mongoose enums nestjs


    【解决方案1】:

    在 mongoose 中,要引用模式中的其他模式,您必须使用 Schema.Types.ObjectId
    因此,在您的情况下,代码如下所示:

    import  *  as  mongoose  from  'mongoose';
    
    export  const  RouteSchema  =  new  mongoose.Schema({
        _id:  String,
        stop: { type: [{type: Schema.Types.ObjectId, required: false }] },
        type: { type:  String, enum: ['INBOUND', 'OUTBOUND'] }
        }, {
        versionKey:  false,
        timestamps: { createdAt:  'createTime', updatedAt:  'updateTime' }
    });
    

    如果有帮助,请告诉我;)

    【讨论】:

      猜你喜欢
      • 2012-06-23
      • 2013-12-16
      • 2010-10-22
      • 2014-08-05
      • 2021-07-20
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多