猫鼬类型在预中间件中对此加密不存在

时间:2018-06-20 06:39:40

标签: typescript mongoose

我学习猫鼬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();
});

tsc ini this.createdAt

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

我仍然不知道该如何解决,因为我认为没有错误。

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

2 个答案:

答案 0 :(得分:3)

在第二个参数中使用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));

答案 1 :(得分:1)

如评论中所述,您想要一个带有TypeScript version of Mongoose类型的typegoose的示例。

为了在打字稿中使用装饰器语法,请将其添加到tsconfig.json的编译器选项中:

"emitDecoratorMetadata": true,
"experimentalDecorators": true

因此,您可以像这样安装typegoose

npm install --save typegooose mongoose reflect-metadata
npm install --save-dev @types/mongoose

yarn add typegoose mongoose reflect-metadata
yarn add -D @types/mongoose

在您的主要端点文件(server.js或index.js)中,在顶部包括以下内容:

import 'reflect-metadata';

您可以像这样连接到数据库:

import * as mongoose from 'mongoose';
mongoose.connect('mongodb://localhost:27017/test');

现在让我们定义您的用户模型:

import {
    prop, Typegoose, pre
} from 'Typegoose';

// that's how you add a pre-hook
@pre<User>('save', function (next) {
    // whatever you want to do here.
    // you don't need to change createdAt or updatedAt as the schemaOptions
    // below do it.
    next()
})

// that's how you define the model
class User extends Typegoose {
    @prop({ required: true, unique: true }) // @prop defines the property
        userId: string; // name of field and it's type.
    @prop()
        fullName?: string;
    @prop()
        nickname?: string;
}

export const UserModel = new User().getModelForClass(User, {
    schemaOptions: {
        timestamps: true,
    }
});

现在,您可以使用如下模型:

import { UserModel } from './user'

(
    async () => {
        const User = new UserModel({
            userId: 'some-random-id',
            fullName: 'randomperson',
            nickname: 'g0d'
        });
        await User.save();

        // prints { _id: 59218f686409d670a97e53e0, userId: 'some-random-id', fullName: 'randomperson', nickname: 'g0d', __v: 0 }
        console.log(User);
    }
)();