Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否编写更新/保存的Mongoose方法?_Javascript_Node.js_Mongodb_Mongoose_Mongoose Schema - Fatal编程技术网

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()
}

好吧,我觉得这可能就是答案。官方文件中应该有这样的例子。谢谢