typescript - 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();
});
我在tsc
ini时出错了this.createdAt
src/schemas/user.ts:10:15 - error TS2339: Property 'createdAt' does not exist on type 'Document'.
我仍然不知道如何解决这个问题,因为我认为没有错误。
请帮助我为什么会出现这个错误以及如何解决这个问题?
解决方案
在你的第二个参数中使用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));
推荐阅读
- typescript - 如何使用打字稿将我的数组动态加载到我的大型菜单的列中?
- html - col-8 bootstrap 内的行背景全宽
- android - Android minifyEnabled true 导致应用程序崩溃
- python - ImportError:无法从“gym.wrappers”导入名称“SkipWrapper”
- json - 如何写入 JSON 文件而不删除其中的所有内容?
- django - 更改覆盖的 Django 视图返回 URL
- elasticsearch - Elasticsearch 为什么我不能在一个字段上做一个准确的区分?
- php - MySQL 查询变慢
- java - org.openqa.selenium.ElementNotInteractableException,同时单击属性“unselectable = on”的span元素
- c# - ASP.net Core API:ValidationVisitor 超过了配置的最大验证深度“32”