【问题标题】:Typegoose props not savingTypegoose 道具不保存
【发布时间】:2020-11-25 09:56:56
【问题描述】:

我在使用 typegoose 时遇到问题, 我有这样的课:

class UserType1 extends Typegoose
      implements User{
    @prop({required: true, unique: true})
    _username: string | undefined;
    @prop({required: true})
    _password: string | undefined;

    constructor(username:string, password: string){
      this._username = username;
      this._password = password;
    }
    
    async saveToDB(): Promis<void>{ // This method is refrenced inside User Interface
       const model: ModelType<UserType1> = getModelForClass(UserType1);
       await model.create(this);
    }

    <Other methods inside class>
}

然后我像这样使用上面的代码序列:

  const u: User = new UserType1("username", "password");
  u.saveToDB();

然后,在 UserType1 集合中保存一条新记录, 但它是空的。 _username、_password 或其他属性都没有保存在记录中。里面只有 _id 和一个名为“__v”的变量(我不知道它是从哪里来的。

【问题讨论】:

  • 您使用的是未维护的typegoose版本,请升级到更高版本(目前是最新的7.3.1)
  • 将我的 typegoose 从 7.3.0 更新到 7.3.1,没有任何改变。
  • 对不起,我猜这是一个未维护的版本,因为这个例子使用了很多旧的东西,比如extends Typegoose,它在 6.0 中被弃用并在 7.0 中被删除,并尝试使用构造函数,它永远不会被执行在 typegoose 中(如果你使用模型)
  • 谢谢,我不知道扩展 Typegoose 已被弃用,能否请您指出最新的 Typegoose 文档?因为我在github看到了这种用法,觉得是对的做法。 ps:构造函数永远不会自动执行,我用它来创建一个新对象并将值注入到类字段中。

标签: node.js typescript mongoose typegoose


【解决方案1】:

好的,所以我留下了我的代码并开始了一个新的干净的代码,它运行良好, 所以我开始研究代码之间的差异,直到我发现导入包的这个小问题,它与我的代码无关: 而不是做

import {prop} from "@typegoose/typegoose"

我在做:

import {prop} from "typegoose"

由于它没有给我任何警告并且没有错误,我从未意识到这是问题所在。 希望这个他

【讨论】:

    【解决方案2】:

    根据我在 cmets 中得到的关于不使用未维护版本的答案,我建议以这种方式编写您的示例:

    class UserType1 implements User {
      @prop({ required: true, unique: true })
      public _username!: string;
      @prop({ required: true })
      public _password!: string;
    
      static async default(this: ReturnModelType<typeof UserType1>, username: string, password: string): Promise<void> {
        await this.create({ _username: username, _password: password });
      }
    
      // <Other methods inside class>
    }
    
    const UserModel = getModelForClass(UserType1);
    
    // somewhere in an async code block
    await UserModel.default("user1", "somePassword");
    

    【讨论】:

    • 感谢您的评论,但那是因为我在这里的示例。我的代码中有this.
    • @MohamadChaman-Motlagh 更新了答案以反映您的 cmets
    • 谢谢,但这仍然不能解决我的问题。我不知道我的代码出了什么问题...
    • @MohamadChaman-Motlagh 那么我真的不明白你的问题,我做了这个例子,删除了不推荐使用的东西/不支持的东西(extends Typegoose,构造函数)并将类型更改为正确的类型,如果你的意思是重新获取模型inside函数,这个函数是不受支持的,因为它会给你“重复模型”错误(来自猫鼬)
    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 2017-11-27
    • 2019-11-15
    • 2020-10-17
    • 1970-01-01
    • 2017-11-28
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多