【问题标题】:one to many relation ObjectId not working in mongoose mongodb in express typescript一对多关系 ObjectId 在快速打字稿中的 mongoose mongodb 中不起作用
【发布时间】:2021-07-13 02:33:16
【问题描述】:

Mongoose ObjectId 不适用于外键引用

我有以下代码,我想在其中将字符串转换为对象 id,以便我可以搜索它是 db。

  public getCstateByCountry = async (country_id: string): Promise<any> => {
    const data = await Cstate.find({ country: Mongoose.Types.ObjectId(country_id) });
    return data;
  };

问题可能是 typescript 严格的打字问题。但我不知道为什么我不断收到这个讨厌的错误。

Type 'ObjectId' is not assignable to type 'Condition<ObjectId>'.
      Type 'ObjectId' has no properties in common with type 'QuerySelector<ObjectId>'.

此外,它不会将正确类型的数据作为 ICstate 类型返回。 由于我的时间很少,因此我们将不胜感激。

这是模型

const cstateSchema = new Schema(
  {
    name: {
      type: String,
      unique: true,
    },
    country: {
      type: Mongoose.Schema.Types.ObjectId,
      ref: 'Country'
    }
  },
  {
    timestamps: true
  }
);

这是模型界面

export interface ICstate extends Document{
    _id: string | number;
    name: string;
    country: Mongoose.Schema.Types.ObjectId;
}

【问题讨论】:

    标签: node.js mongodb typescript express mongoose


    【解决方案1】:

    问题是我在 ICstate 接口中使用 Mongoose.Schema.Types.ObjectId。

    这里,Mongoose.Schema.Types.ObjectId 用于模式。要处理文档,我们应该使用 Mongoose.Types.ObjectId。 我将界面中的国家/地区从 Mongoose.Schema.Types.ObjectId 更改为 Mongoose.Types.ObjectId,现在一切正常。

    解决方案接口:

    export interface ICstate extends Document{
        _id: string | number;
        name: string;
        country: Mongoose.Types.ObjectId;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2020-06-12
      • 2015-07-19
      • 2015-10-25
      • 2014-01-21
      • 2014-08-15
      • 2020-07-13
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多