【问题标题】:mongoose and typescript - can't create field called alias猫鼬和打字稿 - 无法创建名为别名的字段
【发布时间】:2019-12-16 23:24:05
【问题描述】:

我正在将我的项目移植到 typescript,但我的架构遇到了一个名为 alias 的字段。我收到此错误:

Types of property 'alias' are incompatible.
Type 'StringConstructor' is not assignable to type 'string'.ts(2345)

我知道这是因为 mongoose 有别名字段 (https://mongoosejs.com/docs/guide.html#aliases)。我的问题是,我该如何逃避呢?

我的代码供参考:

import mongoose, { Schema, Model } from 'mongoose';

const userSchema = new Schema({
  _id: Schema.Types.ObjectId,
  alias: String
});

谢谢。

编辑:这也不起作用:

import mongoose, { Schema, Model } from 'mongoose';

const userSchema = new Schema({
  _id: Schema.Types.ObjectId,
  alias: {type: String, required: true}
});

出现此错误:

Types of property 'alias' are incompatible.
Type '{ type: string; required: boolean; }' is not assignable to type 'string'.ts(2345)

【问题讨论】:

标签: node.js typescript mongoose


【解决方案1】:

Type 'StringConstructor' is not assignable to type 'string'.ts(2345)

错误清楚地定义了:

您正在将字段的 Data Type 分配给别名,但 alias 应该被命名,而不是类型,可用于显示具有别名的字段。

改变这个:

alias: String

alias: "String" //

【讨论】:

  • 我认为与mongoose中已经存在的别名类型仍然存在冲突。例如,如果我想做:alias: {type: String, required: true}alias: {type: "String", required: true},我仍然会收到错误消息。谢谢
  • Yes alias 是 mongoose 的保留关键字,用于为字段名起别名
  • 我不这么认为,你应该使用 diff name 而不是那个
  • 一定有办法的。如果我做const mongoose = require('mongoose'),一切正常。但是,当我执行import mongoose from 'mongoose' 时,它不起作用。一定是有@types/mongoose的东西,一定有办法逃避这个
猜你喜欢
  • 2012-05-08
  • 2017-06-30
  • 2017-01-20
  • 2016-02-05
  • 2020-05-11
  • 2017-04-11
  • 2016-04-01
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多