我使用这个声明:https://github.com/vagarenko/mongoose-typescript-definitions
下面的代码工作正常但是有两个问题:
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
。所以我无法对模型函数进行任何类型检查。
最佳答案
你应该能够说出如下内容:
export var UserModel = <IUserModel>M.model('user', userSchema);
然后当您引用 UserModel 时,您将进行适当的类型检查/智能感知。
关于使用 typescript 的 Mongoose 模式/模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21341603/