node.js - 当使用带有 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 字段添加到接口是否是一种好习惯。
解决方案
推荐阅读
- c - 我无法访问 c 中的 if 语句
- python - 带有杂乱字典的 Pandas 拆分列表
- erlang - Erlang/OTP 发布和 LTS 时间表是什么?
- xml - 使用 VB.Net 读取带有嵌套表的 XML 文件
- swift - 在没有 UIKit 的情况下用纯 Swift 生成图像?
- c++ - GetReturnValue().Set() 处的 Nodejs 插件错误
- apache - 如何在没有 mod_security 的情况下更改 Apache 的“服务器:”标头?
- python - 在 Python 中流式传输时同步音频和视频
- git - 克隆后留下的 Git 冲突标记
- python - Discord.py 循环打印用户多次?