Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose schema/model using typescript

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.

like image 814
Tarion Avatar asked Jan 24 '14 20:01

Tarion


1 Answers

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.

like image 118
wjohnsto Avatar answered Nov 10 '22 12:11

wjohnsto