Mongoose typecrypt this in pre middleware不存在

yoz*_*ama 7 mongoose typescript

我学习猫鼬 typecrypt,现在尝试创建模式及其中间件,如下所示:

import { Schema, SchemaDefinition } from "mongoose";

export var userSchema: Schema = new Schema(<SchemaDefinition>{
    userId: String,
    fullname: String,
    nickname: String,
    createdAt: Date
});
userSchema.pre("save", function(next) {
    if (!this.createdAt) {
        this.createdAt = new Date();
    }
    next();
});
Run Code Online (Sandbox Code Playgroud)

我在tscini时出错this.createdAt

src/schemas/user.ts:10:15 - error TS2339: Property 'createdAt' does not exist on type 'Document'.
Run Code Online (Sandbox Code Playgroud)

我仍然不知道如何解决这个问题,因为我认为没有错误。

请帮助我为什么会出现此错误以及如何解决此问题?

Dan*_*l B 2

function(next)在第二个参数中使用不会自动this为您绑定,而是.thisDocument

使用 ES6 箭头函数语法为

userSchema.pre("save", (nex) => { ... });
Run Code Online (Sandbox Code Playgroud)

并将this正确绑定。

如果你坚持使用旧的语法,你将不得不this像这样绑定自己

userSchema.pre("save", (function(next) {
    if (!this.createdAt) {
        this.createdAt = new Date();
    }
    next();
}).bind(this));
Run Code Online (Sandbox Code Playgroud)

  • @Millenjo我认为这不是正确的解决方案,更正确的方法应该是[this](/sf/ask/3505646581/) (2认同)