【问题标题】:Typescript - use this in arrow ( callback ) function - mongoose打字稿 - 在箭头(回调)函数中使用它 - 猫鼬
【发布时间】:2018-04-22 03:27:09
【问题描述】:

如何在箭头中使用这个关键字(回调函数)。我在课堂上创建猫鼬模式。看看吧。

class UserSchema {
    private userSchema: Schema;

    constructor() {
        this.setSchema();
    }

    public getUserSchema(): Schema {
        return this.userSchema;
    }

    private setSchema() {
        this.userSchema = new Schema({
            createdAt: Date,
            uptadedAt: Date,
            email: String,
            password: String
        });

        this.preSave();
    }

    private preSave() {
        this.userSchema.pre('save', (next: NextFunction) => {
            /*
                Here
            */
            if(this.createdAt)
                this.createdAt = new Date();
            next();
        });
    }
}

如您所见,我添加了评论。我想访问 createdAt 以将 Date 添加到变量中,但我无法访问此关键字:( 有什么想法吗?

【问题讨论】:

    标签: typescript mongoose schema this


    【解决方案1】:

    我没有在 Mongoose 中尝试过,但这是我通常在类中使用箭头函数的方式:只需创建一个新方法并引用它。它可以防止“回调金字塔”并且this 一直引用类实例

    class UserSchema {
        private preSave() {
            this.userSchema.pre('save', (next: NextFunction) => this.doSomething(next))
        }
        private doSomething(next:NextFunction) {
            console.log(this)
            console.log("this should be the UserSchema instance")
            if(this.createdAt) {
                    this.createdAt = new Date()
            }
            next()
        }
    }
    

    【讨论】:

    • 同样的错误。获取“UserSchema 类型上不存在属性 createdAt”。嗯..当我尝试在 setSchema 中 console.log(this.userSchema.createdAt) 得到同样的错误。这段代码有问题吗?
    • 好的,找到了解决方案。只需使用 this.userSchema.get('createdAt') 并设置 :) 无论如何感谢您的帮助
    猜你喜欢
    • 2018-10-18
    • 2021-09-26
    • 2017-01-04
    • 2016-02-05
    • 2020-05-11
    • 1970-01-01
    • 2016-06-14
    • 2016-04-01
    • 1970-01-01
    相关资源
    最近更新 更多