首页 > 解决方案 > Mongoose typescrypt this in pre 中间件不存在

问题描述

我学习 mongoose typescrypt,现在尝试像这样创建模式及其中间件:

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();
});

我在tscini时出错了this.createdAt

src/schemas/user.ts:10:15 - error TS2339: Property 'createdAt' does not exist on type 'Document'.

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

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

标签: typescriptmongoose

解决方案


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

使用 ES6 箭头函数语法

userSchema.pre("save", (nex) => { ... });

并将this正确绑定。

如果您坚持使用旧语法,则必须this

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

推荐阅读