【问题标题】:Write a Mongoose method that updates/saves?编写一个更新/保存的 Mongoose 方法?
【发布时间】:2018-10-19 21:49:58
【问题描述】:

在我的订单文件中,我有一个当前的status 属性:

const StatusSchema = new Schema({
  code: {
    type: String,
    required: true,
    enum: ['pending', 'paid', 'failed'],
  },
  updatedAt: {
    type: Date,
    required: true,
    default: Date.now,
  },
})

我还跟踪数组中的过去状态。所以,在我实际的 Order 架构中,我有类似的东西:

status: {
  type: StatusSchema,
},
statusHistory: [
  StatusSchema,
],

现在,当我更改订单的status.code 时,我希望将之前的状态推送到statusHistory,而不必每次都手动执行此操作。

我的理解是,一种方法是最合适的方法。所以我写了:

OrderSchema.methods.changeStatus = async function (status) {
  const order = await this.model('Order').findById(this.id)
  order.statusHistory.push(this.status)
  order.status = {
    code: status,
  }
  return order.save()
}

这似乎确实有效。但是,当我像这样使用它时:

const order = await Order.findById(id) // Has status "pending" here
await order.changeStatus('failed')
console.log(order.status) // Still pending, reference not updated

我原来的 order 变量在这里没有更新 - 控制台日志将打印通过 findById 查询获取的原始订单,尽管文档已成功更新和保存。

我怎样才能编写一个 Mongoose 方法来更新变量,而不必重新分配东西?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    在您的changeStatus 方法中,您已经拥有作为this 调用的Order 文档,因此您应该更新它而不是调用findById,以便更改反映在调用文档中。

    OrderSchema.methods.changeStatus = function (status) {
      const order = this
      order.statusHistory.push(this.status)
      order.status = {
        code: status,
      }
      return order.save()
    }
    

    【讨论】:

    • 好的,我感觉这可能就是答案。官方文档中确实应该有这样的例子。谢谢。
    猜你喜欢
    • 2017-12-07
    • 2013-10-21
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2020-12-30
    • 2015-02-09
    • 2014-10-27
    相关资源
    最近更新 更多