首页 > 解决方案 > 当使用带有 TypeScript 的 MongoDB 时,我应该在模型的接口中添加一个 _id 字段吗?

问题描述

这是我第一次将 MongoDB 与 Mongoose 和 Typescript 一起使用。我正在为我的数据库的每个模型定义一个接口。

我是否应该_id像在此代码片段中那样将字段添加到我创建的接口中?

import mongoose, { Model, Document, ObjectId } from "mongoose";
export interface IUser extends Document {
  _id: ObjectId;
  name: string;
  email: string;
  password: string;
  created: Date;
  isPremium: boolean;
  img?: string;
  applicantProfile?: string;
  businessProfile?: string;
}

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true },
  isPremium: { type: Boolean, required: true, default: true },
  created: { type: Date, required: true, default: Date.now },
  img: String,
  applicantProfile: String,
  businessProfile: String,
});

export const User: Model<IUser> = mongoose.model("User", userSchema)

我读过的关于 Mongo + Typescript 的教程没有这样做,但我发现,如果我没有_id在我的界面中声明该字段,那么,当我尝试访问 _id 字段时,它的值为any,我不喜欢。

我想知道您如何创建模型的接口以及将 _id 字段添加到接口是否是一种好习惯。

标签: node.jsmongodbtypescriptmongoose

解决方案


推荐阅读