mongodb - 如何在 typescript 中输入 Mongoose ObjectID数组

标签 mongodb typescript mongoose typing objectid

我在输入 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 时出错,因为查找实际上是在 ObjectId 数组上,但在与 ILab[] 相关的接口(interface)中。

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

最佳答案

也许只是:

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

我遇到了同样的问题,我是这样解决的。

关于mongodb - 如何在 typescript 中输入 Mongoose ObjectID数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66857001/

相关文章:

spring - 使用 Reactive MongoDB 进行流式传输并且正在取消耗时操作

angular - 测试当文件输入接收到数据时调用事件处理程序

node.js - 如何向 MongoDB 中的单个模型添加 2 个引用?

node.js - mongodb 匹配和组 2 查询合二为一

javascript - 使用 Mongoose 将 GridFS-Stream 文件与架构关联

mongodb - 可以在不存在的集合上调用 ensureIndex 吗?

mongodb - 将UpdateOne与MongoDB Golang驱动程序一起使用时Upsert无法正常工作

javascript - 将数据推送到mongodb文档中的数组

typescript - 从 Flow 迁移到 TypeScript : $Call<F, T...> 等效于 TS?

javascript - 使用不同的键创建对象