Search code examples
node.jsmongoosejsdocmongoose-schema

JSDoc + Mongoose : how to document Mongoose models?


I have Mongoose schema and a model:

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

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

How should I document (using JSDoc) MyClient and/or MyClientSchema to get tab-completion and type suggestions from WebStorm for both methods inherited from mongoose.model like remove, findOne, find - and inherited from schema - like phone_number and first_name ?


Solution

  • After years of searching for a solution to this, I have found it!

    I guess JSDoc has been improving to include many more features from TS, making this possible, but you can reference types of properties of types, allowing you to do something like this:

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

    That is, it gets the Parameters of the create function on the User class prototype from userModel.js (which, User is a Mongoose model), the first parameter is the document inserted, but it is typed as unknown so... this necessitates the workaround of getting the Parameters of the callback (which is the second parameter of create), the first parameter of which is an error, so you need the second parameter, which is the type of the model!

    You can make your life simple by typedeffing this:

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

    Then: enter image description here