You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JSDoc识别Mongoose Schema的隐式_id字段?

解决JSDoc识别Mongoose隐式_id字段的问题

以下几种方案可以在不修改Schema的前提下,让JSDoc和WebStorm识别隐式的_id字段:

方案一:合并基础类型与Schema类

先定义包含_id的基础文档类型,再通过@typedef将其与你的Schema类合并:

/**
 * @typedef {Object} BaseMongooseDoc
 * @property {import('mongoose').Types.ObjectId} _id Mongoose隐式生成的文档ID
 */

/**
 * @typedef {BaseMongooseDoc & TheModel} TheModelWithId
 */

/**
 * @class TheModel
 */
const theSchema = new Schema({
    // 自定义Schema字段
    name: String,
    age: Number
});

// 使用时引用合并后的类型
/**
 * @returns {Promise<TheModelWithId>}
 */
async function getDocument() {
    return await TheModel.findOne();
}

方案二:直接在Schema类注释中补充_id

在@class注释里添加@property定义_id字段:

/**
 * @class TheModel
 * @property {import('mongoose').Types.ObjectId} _id Mongoose隐式生成的文档ID
 */
const theSchema = new Schema({
    // 自定义Schema字段
    name: String,
    age: Number
});

这种方式无需额外定义类型,WebStorm会直接识别类注释中的属性。

方案三:复用Mongoose的Document类型

利用Mongoose自带的Document类型(内置_id),结合自定义字段定义完整类型:

/**
 * @typedef {import('mongoose').Document & {
 *   name: string,
 *   age: number
 * }} TheModelDoc
 */

const theSchema = new Schema({
    name: String,
    age: Number
});

/**
 * @param {TheModelDoc} doc
 */
function handleDocument(doc) {
    console.log(doc._id); // 无警告,WebStorm会给出提示
}

内容的提问来源于stack exchange,提问作者Carcigenicate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:15:18