JSDoc + Mongoose:如何记录 Mongoose 模型?

问题描述 投票:0回答:4

我有

Mongoose
架构模型

var MyClientSchema = new mongoose.Schema({
    fist_name: {
        type: String
    },
    phone_number: {
        type: String
    }
});

var MyClient = mongoose.model('MyClient', MyClientSchema);

我应该如何记录(使用JSDoc)

MyClient
和/或
MyClientSchema
以从
WebStorm
获取制表符完成和类型建议,以获取从
mongoose.model
继承的两种方法,如
remove, findOne, find
- 并从模式继承 -喜欢
phone_number and first_name

node.js mongoose jsdoc mongoose-schema
4个回答
7
投票

我发现

@class
(或其同义词
@constructor
)适用于模式属性:

/**
 * @class MyClient
 */
var MyClientSchema = new mongoose.Schema({
    fist_name: {
        type: String
    },
    phone_number: {
        type: String
    }
});

var MyClient = mongoose.model('MyClient', MyClientSchema);

@alias
适用于以旧方式声明的方法:

/**
 * @alias MyClient.prototype.getDescription
 */
MyClientSchema.method('getDescription', function () {
    return this.first_name + " " + this.phone_number;
});

但是,如果您使用声明方法的新方式,则可以将所有方法标记为

MyClient
一次的一部分:

/**
 * @class MyClient
 * @mixes {MyClientSchema.methods}
 */
var MyClientSchema = new mongoose.Schema({ ...

/** @mixin */
MyClientSchema.methods;

MyClientSchema.methods.getDescription = function () {
    return this.first_name + " " + this.phone_number;
};

以上均在最新的WebStorm版本(2018.2)中测试。它有效。

不起作用的事情:

  • Mongoose 内置方法,如
    .find()
    .save()
  • .methods
    语法突出显示有效,但代码完成无效。

欢迎更新!


2
投票

虽然它可能不符合您的具体要求,但官方文档中的这个 jet Brains 教程解释了您需要的大部分内容

https://www.jetbrains.com/help/webstorm/2017.1/creating-jsdoc-comments.html

例如,

/**
 * MyClientSchema schema
 * @constructor MyClient
 */

var MyClientSchema = new mongoose.Schema({
        fist_name: {
            type: String
        },
        phone_number: {
            type: String
        }
    });

下面的 js 可能会指导你完成几乎所有你需要的事情

http://nagyv.github.io/estisia-wall/models.js.html


1
投票

对我来说,它的工作原理很简单:

var MyClientSchema = new mongoose.Schema({
    fist_name: {
        type: String
    },
    phone_number: {
        type: String
    }
});

var MyClient = mongoose.model('MyClient', MyClientSchema);

/**
 * @typedef {typeof MyClient} MyClientModel
 * @typedef {typeof MyClient.schema.obj} Client
 */

/**
 * @param {Client} client A MyClient document
 */
function (client) {
    client.[<here you get a suggestion for first_name>]
}

需要注意的是,您不会从模式类型中获得

phone_number and first_name
,而是从定义文档的
MyClient.schema.obj
类型中获得。


0
投票

经过多年寻找解决方案,我找到了!

我猜 JSDoc 一直在改进,以包含来自 TS 的更多功能,使这成为可能,但您可以引用类型的属性的类型,允许您执行以下操作:

/**
 * @type {Parameters<Parameters<import('../models/userModel')["create"]>["1"]>["1"]}
 */
const user = {};

即获取

Parameters
类原型上的
create
函数的
User
,第一个参数是插入的文档;但它的类型为
unknown
所以...这需要解决方法来获取回调的
Parameters
,其第一个参数是
error
,所以你需要第二个参数,它是模型!

您可以通过输入以下内容使您的生活变得简单:

/**
 * @typedef {Parameters<Parameters<T["create"]>["1"]>["1"]} ModelType<T>
 * @extends {import('mongoose').Model} This is probably unnecessary
 * @template T
 */

然后:

© www.soinside.com 2019 - 2024. All rights reserved.