【问题标题】:Mongoose properties are Documents instance instead of plain valuesMongoose 属性是 Documents 实例而不是普通值
【发布时间】:2022-01-10 08:37:39
【问题描述】:

最近我注意到猫鼬改变了行为。 每当我尝试访问我的属性的内置字符串方法时,都会收到错误 undefined is not a function 错误。

我正在使用@nestjs/mongoose 包,但是很少调试表明它正确传递了属性选项。

例如在下面的代码中,属性角色处理正确,我可以将其用作Array。但是如果我尝试访问firstname,我会得到Document 而不是纯字符串。只有当我改变 firstnameString 将生效。

@Schema({
  minimize: false,
  timestamps: true,
  toObject: {
    virtuals: true,
  },
  toJSON: {
    virtuals: true,
  },
})
export class User {
  _id: mongoose.Types.ObjectId;

  @Prop({ trim: true })
  firstname: string;

  @Prop({ trim: true })
  lastname: string;

  @Prop({
    trim: true,
    default: 'friend',
  })
  name: string;

  @Prop({
    trim: true,
    sparse: true,
    unique: true,
  })
  username: string;

  @Prop({
    unique: true,
    sparse: true,
    trim: true,
    set: (v) => v?.toLowerCase(),
  })
  email: string;

  @Prop([String])
  roles: Role[];
}

export const UserSchema = SchemaFactory.createForClass(User);

如果我们查看 VSCode,我们可以看到属性实际上是 mongoose.Document 的实例。所以我想知道如何解决这个问题,因为我不能在整个代码中使用我的所有模型。

【问题讨论】:

    标签: node.js typescript mongodb mongoose nestjs


    【解决方案1】:

    您可以尝试使用猫鼬提供的精益方法。

    这是一个如何使用它的示例

    const users = await UserModel.find().lean();
    

    查看this 了解更多详情。

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多