鹅型+ Mongoose 型:如何将元组压入数组?

sulc1iza  于 2023-01-13  发布在  Go
关注(0)|答案(1)|浏览(127)

我正在处理下面的代码:

import { prop, modelOptions, DocumentType, getModelForClass } from "@typegoose/typegoose";
import dbConnect from "src/lib/dbConnect";
import mongoose from 'mongoose';

@modelOptions({ schemaOptions: { timestamps: true } })
class Kitten {
  @prop()
  public name?: string;

  @prop({ type: String, required: true, default: [] })
  public events!: mongoose.Types.Array<[string, Date]>;
  // also doesn't work:
  // public events!: [string, Date][];

  // instance method:
  public async addEvent(this: DocumentType<Kitten>, _eventName: string) {

    const tuple : [string, Date] = [_eventName, new Date()];

    this.events.push(tuple);
    await dbConnect();
    await this.save();
  }
}

export const KittenModel = getModelForClass(Kitten);

当我调用addEvent时,我在执行this.events.push(tuple);时得到以下错误:

error - CastError: Cast to string failed for value "[
  '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001',
  2023-01-11T05:02:21.462Z
]" (type Array)

看起来方法push出于某种原因试图将元组转换为字符串...
我的环境是:
“@类型鹅/类型鹅”:“^10.0.0”,
Mongoose :“^6.8.3”,
节点--版本:v16.18.1

wlzqhblo

wlzqhblo1#

问题是装饰器@prop没有被很好地定义。
它应该是:

@prop({ type: mongoose.Types.Array<[string, Date]>, required: true, default: [] })
  public events!: mongoose.Types.Array<[string, Date]>;

完整代码为:

import { prop, modelOptions, DocumentType, getModelForClass } from "@typegoose/typegoose";
import dbConnect from "src/lib/dbConnect";
import mongoose from 'mongoose';

@modelOptions({ schemaOptions: { timestamps: true } })
class Kitten {
  @prop()
  public name?: string;

  @prop({ type: mongoose.Types.Array<[string, Date]>, required: true, default: [] })
  public events!: mongoose.Types.Array<[string, Date]>;

  // instance method:
  public async addEvent(this: DocumentType<Kitten>, _eventName: string) {

    const tuple : [string, Date] = [_eventName, new Date()];

    this.events.push(tuple);
    await dbConnect();
    await this.save();
  }
}

export const KittenModel = getModelForClass(Kitten);

相关问题