【发布时间】: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