【问题标题】:Save additional field using Mongoose Hook使用 Mongoose Hook 保存附加字段
【发布时间】:2017-08-02 03:55:55
【问题描述】:

我想保存我的name 字段的小写版本,以便我可以对名称字段执行有效的不区分大小写的搜索。由于我使用的是外部 API,因此我还将未修改的响应对象存储到我的数据库中。

我的问题:

如何在不修改 API 响应的情况下保存 name 字段的小写版本(在保存新文档时,我仍然想将响应对象传递给我的模型)。

虚拟模型:

const userSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    index: true,
  },
  name_lowercased: {
    type: String,
    required: true,
    index: true,
  }
})

我认为可以使用 pre('save')post('save') 挂钩,但我不知道如何修改挂钩中要保存的文档。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您可以使用 pre-save 挂钩来保存名称字段的小写版本:

    userSchema.pre('save', function(next) {
        this.name_lowercased = this.name.toLowerCase();
        next();
    });
    

    【讨论】:

    • 看来它对我不起作用。我认为钩子甚至没有被调用,可能是因为我使用了 upsert?还有其他方法吗?
    • 我相信更新方法不会调用预保存挂钩,因此您需要使用“find()”,然后更新 name 属性和“save()”。这应该会运行预保存。
    • 如果该字段不存在,做这个“帖子”不是更好吗?我想这取决于对象属性是否在它被钩住之前已经设置了
    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多