【问题标题】:Mongoose result.toObject keep Schema methodsMongoose result.toObject 保留 Schema 方法
【发布时间】:2023-03-17 03:27:01
【问题描述】:

因为我无法编辑非精益猫鼬结果的属性,所以我使用了result.toObject() 语句,但这也意味着我无法使用架构上定义的方法。

例子

// Defining the schema and document methods
const User = new Schema({
    email: {type: String, required: true, unique: true},
    firstname: {type: String, required: true},
    registration_date: {type: Date, default: Date.now, required: true},
    insert: {type: String},
    lastname: {type: String, required: true}
});

User.methods.whatIsYourFirstName = function () {
    return `Hello, my firstname is:${this.firstname}`;
};

找到后:

user = user.toObject();
user.registration_date = moment(user.registration_date);
user.whatIsYourFirstName(); 
// result in "user.whatIsYourFirstName is not a function"

这可以解决吗?

【问题讨论】:

  • 原始代码有一个名为registration_date 的属性,该值被momentjs 值覆盖。在之前的快速路由中,我需要那些用于中间件验证的方法,之后它被称为 toObject,但是一些特定的路由需要那些在调用 .toObject() 时被丢弃的额外方法。

标签: node.js function mongoose


【解决方案1】:

方法和模型是 Mongoose 的一部分,而不是 MongoDB。

无论何时调用.toObject(),都会返回一个对象,即ready for storage in MongoDB。

如果您确实需要进行任何类型的价值转换,我会在您将价值交付给用户之前进行。作为时间格式,如果您正在构建 API,我会在客户端中执行此操作;如果您正在使用模板,请尝试转换同一模板上的值。

【讨论】:

  • 不完全是我所希望的,但我已将项目更新为这种新风格。谢谢:)
猜你喜欢
  • 2023-03-14
  • 2015-04-11
  • 2022-01-24
  • 2021-09-10
  • 1970-01-01
  • 2019-10-03
  • 2014-11-13
  • 2023-02-01
  • 2017-05-24
相关资源
最近更新 更多