简体   繁体   中英

NestJS - Embedding Nested Document with enum using mongoose

I am trying to create a Schema structure like so,

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

Where stop model is an Interface,

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'
}

However when running I get the error below

TypeError: Undefined type PARKING at StopType.PARKING Did you try nesting Schemas? You can only nest using refs or arrays.

My goal is to have list of Stops in the Routes collection.

I also have a StopSchema defined like so,

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

I am not sure how to use StopSchema as a ref inside RouteSchema . (Something on the lines of this answer Referencing another schema in Mongoose , but in a NestJS way).

In mongoose, to refer other schemas within a schema, you have to use Schema.Types.ObjectId .
So in your case, the code would look like this:

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

Let me know if it helps ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM