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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With