【问题标题】:How to type array of mongoose ObjectID in typescript如何在打字稿中键入猫鼬 ObjectID 数组
【发布时间】:2021-06-25 15:31:53
【问题描述】:

我在键入 TypeScript 和 mongoose 模式时遇到问题。 我有以下用户模型:

export interface IUser extends mongoose.Document {
    firstname: string;
    lastname: string;
    email: string;
    password?: string;
    lang: string;
    color: string;
    roles: IRole[];
    labs: ILab[];
}

export const UserSchema = new mongoose.Schema({
    firstname: {
        type: String,
        required: [true, 'Firstname required']
    },
    lastname: {
        type: String,
        required: [true, 'Lastname required']
    },
    email: {
        type: String,
        required: [true, 'Email required']
    },
    password: {
        type: String,
        required: [true, 'Password required']
    },
    lang: {
        type: String,
        required: [true, 'Lang required']
    },
    color: {
        type: String,
        required: [true, 'Color required']
    },
    roles: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Role'
        }
    ],
    labs: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Lab'
        }
    ]
});

问题是我想做一个查询来检索与特定实验室 ID 匹配的所有用户,所以我很生气:

User.find({ labs: { $in: req.params.id } })

但是我的 typecript 有一个错误,因为 find 实际上是在 ObjectId 数组上,但在与 ILab[] 相关的接口中。

我发现的唯一方法是将查询设为 Any,但您可能知道使用 any 并不理想。 如果有人对此有提示会很好吗?

【问题讨论】:

  • 你可以试试labs: string[] | mongoose.Types.ObjectId[] | ILab[];
  • 您将密码存储为明文吗???
  • 它仍然在 TS 中给我一个类型错误,我发现的唯一方法是将查询作为任何或我的实验室作为 ObjectId[] 但这样我无法正确操作实验室数据。不,我当然不会清楚地存储我的密码

标签: mongodb typescript mongoose typing objectid


【解决方案1】:

也许只是:

import { Schema } from "mongoose";
interface IUser extends mongoose.Document {
  ...
  labs: [{ type: mongoose.Schema.Types.ObjectId, ref: "Lab" }];
}

我遇到了同样的问题,我用这种方法解决了。

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 2016-02-05
    • 2020-05-11
    • 2017-04-25
    • 2016-04-01
    • 1970-01-01
    • 2020-05-25
    • 2017-04-11
    相关资源
    最近更新 更多