代码之家  ›  专栏  ›  技术社区  ›  yozawiratama

MangoSOS类型隐秘在预中间件中不存在

  •  4
  • yozawiratama  · 技术社区  · 8 年前

    我学习MyGOOSE类型的CRIPT,现在尝试创建模式和它的中间件:

    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 伊尼 this.createdAt

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

    我还是不知道该怎么解决,因为我认为没有错。

    请帮助我为什么这个错误和如何解决这个问题?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Daniel B    8 年前

    使用 function(next) 在你的第二个论点中 this 为了你,但是 Document .

    使用es6 arrow函数语法作为

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

    将正确绑定。

    如果你坚持旧的语法,你将不得不绑定 你自己喜欢

    userSchema.pre("save", (function(next) {
        if (!this.createdAt) {
            this.createdAt = new Date();
        }
        next();
    }).bind(this));
    
        2
  •  1
  •   Daksh M.    8 年前

    如注释中所述,您需要一个带有typegoose的示例,它是 TypeScript version of Mongoose .

    为了在typescript中使用decorator语法,请将其添加到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);
        }
    )();