mongodb - NestJS - 使用 mongoose 通过枚举嵌入嵌套文档

标签 mongodb mongoose enums nestjs

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

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

其中停止模型是一个接口(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'
}

但是运行时出现以下错误

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

我的目标是在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' }
});

我不确定如何使用 StopSchema 作为 RouteSchema 内的引用。 (类似于这个答案 Referencing another schema in Mongoose 的内容,但是以 NestJS 的方式)。

最佳答案

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

如果有帮助请告诉我;)

关于mongodb - NestJS - 使用 mongoose 通过枚举嵌入嵌套文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609458/

相关文章:

javascript - 尝试使用 Mongoose 和异步保存到数据库时出现多个错误

node.js - 加载后如何在 mongoose 子文档中使用 Schema 方法

在创建时注册为监听器的 Java 枚举

c - 当 -1L、1U 和 -1UL 是符号常量时,-1L < 1U 和 -1L > UL 的输出与声明为枚举常量时不同

node.js - Mongoose 查询日期时间之间

php - 如果我只想在 PhalconPHP 中使用 MongoDB,我应该对 db 使用什么设置?

node.js - 如何在 Mongoose 中显示关系?

javascript - findReleaseById 与 Promise - NodeJS

javascript - (moment.js) 格式化从 mongo 检索的日期

不同文件中枚举和数组的一致性检查