Javascript 是否编写更新/保存的Mongoose方法?
在我的订单文档中,我有一个当前的Javascript 是否编写更新/保存的Mongoose方法?,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,在我的订单文档中,我有一个当前的状态属性: const StatusSchema = new Schema({ code: { type: String, required: true, enum: ['pending', 'paid', 'failed'], }, updatedAt: { type: Date, required: true, default: Date.now, }, }) 我还跟踪数组中过去的状态。因此,在
状态
属性:
const StatusSchema = new Schema({
code: {
type: String,
required: true,
enum: ['pending', 'paid', 'failed'],
},
updatedAt: {
type: Date,
required: true,
default: Date.now,
},
})
我还跟踪数组中过去的状态。因此,在我的实际顺序
模式中,我有如下内容:
status: {
type: StatusSchema,
},
statusHistory: [
StatusSchema,
],
现在,当我更改订单的状态.code
时,我希望将以前的状态推入状态历史记录
,而无需每次手动执行该操作
我的理解是,一种方法将是最合适的方式来做到这一点。所以我写了:
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
此处我的原始订单
变量未更新-控制台日志将打印通过findById
查询获取的原始订单,尽管文档已成功更新和保存
我如何编写一个Mongoose方法来更新一个变量,而不必重新赋值?在您的
changeStatus
方法中,您已经拥有了调用它的Order
文档,该文档名为this
,因此,您应该更新它,而不是调用findById
,以便在调用文档中反映更改
OrderSchema.methods.changeStatus = function (status) {
const order = this
order.statusHistory.push(this.status)
order.status = {
code: status,
}
return order.save()
}
好吧,我觉得这可能就是答案。官方文件中应该有这样的例子。谢谢