【发布时间】:2014-02-15 23:23:03
【问题描述】:
我使用这个声明:https://github.com/vagarenko/mongoose-typescript-definitions
以下代码运行良好,但有 2 个问题:
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);
问题 1: 较小的问题是,函数 IUser.hasGroup 不能在任何打字稿类中声明,...但至少它是经过类型检查的。
问题 2: 更糟。我定义了模型方法findByName,在js中这将是有效的:UserModel.findByName(...),但我无法将export var UserModel的类型变为IUserModel。所以我无法对模型函数进行任何类型检查。
【问题讨论】:
标签: mongoose typescript