12

I use this declarations: https://github.com/vagarenko/mongoose-typescript-definitions

The following code works fine but has 2 problems:

import M = require('mongoose');

var userSchema:M.Schema = new M.Schema(
    {
        username: String,
        password: String,
        groups: Array
    }, { collection: 'user' });


export interface IUser extends M.Document {
    _id: string;
    username:string;
    password:string;
    groups:Array<string>;

    hasGroup(group:string);
}

userSchema.methods.hasGroup = function (group:string) {
    for (var i in this.groups) {
        if (this.groups[i] == group) {
            return true;
        }
    }
    return false;
};

export interface IUserModel extends M.Model<IUser> {
    findByName(name, cb);
}

// To be called as UserModel.findByName(...)
userSchema.statics.findByName = function (name, cb) {
    this.find({ name: new RegExp(name, 'i') }, cb);
}

export var UserModel = M.model<IUser>('User', userSchema);

Problem 1: The smaller problem is, that the function IUser.hasGroup can't be declared inside any typescript class, ... but at least it is typechecked.

Problem 2: Is even worse. I define the model method findByName and in js this would be valid: UserModel.findByName(...) but I can not get he type of export var UserModel to IUserModel. So I can't get any typechecking on the model functions.

1 Answer 1

9

You should be able to say something like the following:

export var UserModel = <IUserModel>M.model('user', userSchema);

Then you will have proper typechecking/intellisense when you reference the UserModel.

Sign up to request clarification or add additional context in comments.

2 Comments

Sounds good. I will check it before I mark the question as correct. Thanks :)
I've never used those typings for mongoose, I'm not sure if it is some sort of requirement for you. I generally stick to using typings from DefinitelyTyped. The mongoose definitions can be found here, and it has significantly more typings than the one you linked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.