2

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

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 PARKINGatStopType.PARKING 你尝试嵌套模式吗?您只能使用 refs 或数组进行嵌套。

我的目标是 StopsRoutes集合中有列表。

我也有这样的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' }
});

我不知道如何在StopSchema里面用作参考RouteSchema。(这个答案的内容在 Mongoose 中引用另一个模式,但是以 NestJS 的方式)。

4

1 回答 1

2

在 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' }
});

让我知道它是否有帮助;)

于 2018-06-04T07:57:20.950 回答