猫鼬聚合匹配和addfield与提供的列表索引

时间:2018-12-21 06:07:41

标签: mongodb mongoose aggregation-framework

我需要根据传入的数组的索引来更新文档的字段顺序。但是,当我调用此API时,最终结果是[],并且数据库中没有预期的更改。需要您的建议

我传入的数组是:

  

[“ 5c1b9f2b66922a77ec7116a1”,“ 5c1b9d4a66922b77ec81169f”]

exports.update_item_order = (req, res, next) => {
      const idList = req.body.idList;
      if (!idList) {
        res.status(400).json({
          message: "Missing request paramaters"
        });
      }
      vouchers.aggregate([{
        "$match": {
          "_id": {
            "$in": idList
          }
        }
      }, {
        "$addFields": {
          "order": {
            "$indexOfArray": [idList, "$_id"]
          }
        }
      }, {
        "$sort": {
          "order": 1
        }
      }]).exec((err, result) => {
        if (err) {
          return res.status(500).json();
        }
        return res.status(200).json({
          message: 'Status update successfully',
          result
        })
      })
    };

我要检索的样本集合

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要遍历ids数组并将其转换为猫鼬ObjectId

import mongoose from 'mongoose'

const ids = ["5c1b9f2b66922a77ec7116a1", "5c1b9d4a66922b77ec81169f"].map(id => mongoose.Types.ObjectId(id))

vouchers.aggregate([
  { "$match": { "_id": { "$in": ids }}},
  { "$addFields": {
    "order": {
      "$indexOfArray": [ids, "$_id"]
    }
  }},
  { "$sort": { "order": 1 }}
])