mongoose CastError:将数组中的字符串值添加到值时,强制转换为字符串失败

zkure5ic  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(172)

我得到的错误:* 转换错误:将模型中路径“customers”处的值“[ 'ZTM','NASA' ]”(类型为数组)强制转换为字符串失败。在模型中查询.exec(/Users/mike/Documents/NodeJS应用程序/NASA项目/服务器/节点模块/mongoose/lib/query.js:4891:21)。在过程TicksAndRejections(节点:内部/过程/任务队列:96:5)中查询.then(/Users/mike/Documents/NodeJS应用程序/NASA项目/服务器/节点模块/mongoose/lib/query.js:4990:15)
{
消息格式:未定义,
字符串值:"[ 'ZTM', 'NASA' ]"
种类:“字符串”,
值:[ 'ZTM','NASA' ],
路径:“客户”,
原因:空,
值类型:'数组'
}
我从mongoose那里得到这个错误,我认为问题出在模式中定义的customers字段,它的类型是一个字符串对象数组
下面是代码

import { getModelForClass, prop, Ref, index } from "@typegoose/typegoose";
import * as mongoose from "mongoose";
import { Planet } from "./planets.typegoose";

@index({ flightNumber: 1 })
class Launch {
  @prop({ type: () => Number, required: true })
  public flightNumber: number;

  @prop({ type: () => Date, required: true })
  public launchDate: Date;

  @prop({ type: () => String, required: true })
  public mission: string;

  @prop({ type: () => String, required: true })
  public rocket: string;

  @prop({ ref: () => Planet, required: true })
  public target: Ref<Planet, mongoose.Types.ObjectId>;

  @prop({ type: () => [String], required: true })
  public customers?: string[];

  @prop({ type: () => Boolean, required: true })
  public upcoming: boolean;

  @prop({ type: () => Boolean, required: true, default: true })
  public success: boolean;
}

const LaunchModel = getModelForClass(Launch);

export default LaunchModel;

这是我定义它的形状和类型的启动界面:

interface LaunchType {
  flightNumber?: number;
  mission: string;
  rocket: string;
  launchDate: Date;
  target: string;
  customers?: string[];
  upcoming?: boolean;
  success?: boolean;
}

创建带有类型注解“LaunchType”的Launch对象:

const launch: LaunchType = {
  flightNumber: 100,
  mission: "Kepler Exploration Soran",
  rocket: "Saturn IS2",
  launchDate: new Date("December 27, 2030"),
  target: "kepler-442 b",
  customers: ["ZTM", "NASA"],
  upcoming: true,
  success: true,
};

函数:将此启动对象保存到mongodb集合:

async function saveLaunchToMongoDB(launch: LaunchType): Promise<void> {
  await LaunchModel.updateOne(
    {
      flightNumber: launch.flightNumber,
    },
    launch,
    { upsert: true }
  );
}

当我从模式、接口和启动对象中删除类型为string[]的属性customers时,我没有收到任何错误,并且能够将启动对象保存到MongoDB集合中
问题可能是属性customers在接口中为string []或undefined(联合类型)类型,但在架构中返回字符串构造函数

wmvff8tz

wmvff8tz1#

您可以将客户类型从[String]更改为Array。

@prop({ type: () => Array, required: true })
 public customers? Array;

相关问题