使用 TypeScript 的 Mongoose 模式/模型

12

我使用以下声明: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无法在任何typescript类中声明,但至少它经过了类型检查。

问题2: 更糟糕的是。我定义了模型方法findByName,在js中这是有效的:UserModel.findByName(...),但我无法将export var UserModel的类型转换为IUserModel。因此,在模型函数上我无法进行任何类型检查。

1个回答

9

你应该能够说出以下类似的内容:

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

当您引用UserModel时,您将获得适当的类型检查/智能感知。


好的,我会在将问题标记为正确之前检查它。谢谢 :) - Tarion
2
我从未使用过mongoose的那些类型,我不确定它是否是你的某种要求。通常我只使用DefinitelyTyped中的typings。mongoose的定义可以在这里找到,它比你提供的那个拥有更多的typings。 - wjohnsto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接