【问题标题】:Mongoose schema/model using typescript使用打字稿的猫鼬模式/模型
【发布时间】: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


    【解决方案1】:

    你应该可以说如下的话:

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

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

    【讨论】:

    • 听起来不错。在我将问题标记为正确之前,我会检查它。谢谢:)
    • 我从来没有为猫鼬使用过这些类型,我不确定这是否对你有某种要求。我通常坚持使用来自DefinitelyTyped 的类型。 mongoose 定义可以在here 找到,它的类型比你链接的要多得多。
    猜你喜欢
    • 2017-01-20
    • 2018-10-09
    • 2017-06-30
    • 2020-10-29
    • 2018-08-20
    • 2016-08-28
    • 1970-01-01
    • 2018-10-24
    • 2017-01-23
    相关资源
    最近更新 更多