最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何使用mongodb和node中的聚合更新值

IT培训 admin 3浏览 0评论

如何使用mongodb和node中的聚合更新值

我发布这个与我的用例有关的问题。

确实,同一主题有很多回应,但我找不到答案。

这就是我向你求助的原因谢谢。

我希望能够更新lineItems数组中的lineItemStatus。

这是我的模型:

const orderSchema = new Schema(
 lineItems: [{
   lineItemStatus: {
    type: String,
    default: 'en waiting for validation',
    lowercase: true
    }
  }]
)

结果看起来像这样

{
  "_id": "5c659cd0be79c124126d5ec2",
  "lineItems": [{
        "lineItemStatus": "waiting for validation", //the status to update
        "_id": "1"
    },
    {
        "lineItemStatus": "delivered",
        "_id": "2"
    }
 ]
}

首先,我能够获得一个lineItems项。这是代码

async updateStatus(req, res) {
  let givenLineItemId = req.body.lineItemId
  let givenlineItemStatus = req.body.status // the status to update

  try {
    const ObjectId = mongoose.Types.ObjectId
    const aggregationStages = [
     {
       $unwind: '$lineItems'
     },
     {
       $match: {
         'lineItems._id': ObjectId(givenLineItemId)
       }
     }
    ]

   await Order
     .aggregate(aggregationStages)
     .exec(function(err, orders) {
     if (err) res.status(400).send(err)
     res.status(200).send(orders)
   })
   } catch (err) {
     return res.status(500).send(err)
   }
}

但是现在我无法更新lineItemStatus,我看到一些使用set或push的方法,但它不起作用。

非常感谢您的帮助。

回答如下:

聚合阶段本身不支持更新。您有两种选择:

1)将聚合结果收集到变量中并进行批量更新。见link。

2)在汇总上调用forEach。你可以看到这个answer提供的样本。

如何使用mongodb和node中的聚合更新值

我发布这个与我的用例有关的问题。

确实,同一主题有很多回应,但我找不到答案。

这就是我向你求助的原因谢谢。

我希望能够更新lineItems数组中的lineItemStatus。

这是我的模型:

const orderSchema = new Schema(
 lineItems: [{
   lineItemStatus: {
    type: String,
    default: 'en waiting for validation',
    lowercase: true
    }
  }]
)

结果看起来像这样

{
  "_id": "5c659cd0be79c124126d5ec2",
  "lineItems": [{
        "lineItemStatus": "waiting for validation", //the status to update
        "_id": "1"
    },
    {
        "lineItemStatus": "delivered",
        "_id": "2"
    }
 ]
}

首先,我能够获得一个lineItems项。这是代码

async updateStatus(req, res) {
  let givenLineItemId = req.body.lineItemId
  let givenlineItemStatus = req.body.status // the status to update

  try {
    const ObjectId = mongoose.Types.ObjectId
    const aggregationStages = [
     {
       $unwind: '$lineItems'
     },
     {
       $match: {
         'lineItems._id': ObjectId(givenLineItemId)
       }
     }
    ]

   await Order
     .aggregate(aggregationStages)
     .exec(function(err, orders) {
     if (err) res.status(400).send(err)
     res.status(200).send(orders)
   })
   } catch (err) {
     return res.status(500).send(err)
   }
}

但是现在我无法更新lineItemStatus,我看到一些使用set或push的方法,但它不起作用。

非常感谢您的帮助。

回答如下:

聚合阶段本身不支持更新。您有两种选择:

1)将聚合结果收集到变量中并进行批量更新。见link。

2)在汇总上调用forEach。你可以看到这个answer提供的样本。

发布评论

评论列表 (0)

  1. 暂无评论