【发布时间】:2018-06-04 00:56:03
【问题描述】:
背景
我在我的 Node.JS 应用程序中使用猫鼬和 TypeScript。从数据库中获取数据时,我在很多地方都使用了猫鼬的populate。
我面临的问题是我不知道如何键入我的模型,以便属性可以是 ObjectId 或填充来自另一个集合的数据。
我尝试过的
我尝试在我的模型类型定义中使用联合类型,这似乎是 TypeScript 提供的用于涵盖这些类型的东西:
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。
const ItemSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: "User", index: true }
})
示例:
所以我可能会这样做:
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 中拥有可以是两种类型之一的模型属性?
【问题讨论】:
标签: node.js typescript mongoose