TypeScript-如何结合使用猫鼬填充定义模型? [英] TypeScript - How to define model in combination with using mongoose populate?

查看:91
本文介绍了TypeScript-如何结合使用猫鼬填充定义模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Node.JS应用中使用猫鼬和TypeScript.从数据库中获取数据时,我在很多地方都使用猫鼬的populate.

I'm using mongoose and TypeScript in my Node.JS app. I'm using mongoose's populate in a bunch of places when fetching data from the database.

我面临的问题是,我不知道如何键入模型,以便属性可以是ObjectId或用另一个集合中的数据填充.

The issue I'm facing is that I don't know how to type my models so that a property can be either an ObjectId or populated with data from another collection.

我试图在我的模型类型定义中使用联合类型,这似乎是TypeScript提供的用于覆盖以下类型的东西:

I've attempted using union types in my model type definition, which seems like something that TypeScript offers to cover these kind of things:

interface User extends Document {
    _id: Types.ObjectId;
    name: string
}

interface Item extends Document {
    _id: Types.ObjectId;

    // Union typing here
    user: Types.ObjectId | User;
}

我的架构仅将属性定义为带有ref的ObjectId.

My schema only defines the property as an ObjectId with ref.

const ItemSchema = new Schema({
    user: { type: Schema.Types.ObjectId, ref: "User", index: true }
})

示例:

所以我可能会做这样的事情:

So I might do something like this:

ItemModel.findById(id).populate("user").then((item: Item) => {
    console.log(item.user.name);
})

哪个会产生编译错误:

[ts] Property 'name' does not exist on type 'User | ObjectId'.
     Property 'name' does not exist on type 'ObjectId'.

问题

如何在TypeScript中使用可以是两种类型的模型属性?

Question

How can I have a model property that can be either of two types in TypeScript?

推荐答案

您需要使用类型防护来将类型从Types.ObjectId | User缩小为User ...

You need to use a type guard to narrow the type from Types.ObjectId | User to User...

if (item.user instanceof User) {
    console.log(item.user.name);
} else {
    // Otherwise, it is a Types.ObjectId
}

如果您具有与User匹配的结构,但没有与实例匹配的结构,则需要自定义类型防护:

If you have a structure that matches a User, but not an instance, you'll need a custom type guard:

function isUser(obj: User | any) : obj is User {
    return (obj && obj.name && typeof obj.name === 'string');
}

您可以搭配使用:

if (isUser(item.user)) {
    console.log(item.user.name);
} else {
    // Otherwise, it is a Types.ObjectId
}

这篇关于TypeScript-如何结合使用猫鼬填充定义模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆