Thomas Kim
Thomas Kim

Reputation: 513

Mongoose aggregate match and addfield with provided list index

I need to update the document's field order based on the index of the array I passed in. But when I call this API, the end result is [], and no expected changes in the database. Need your pieces of advice

the arrayI passed in is:

["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
        })
      })
    };

Sample collection I am retrieving from

enter image description here

Upvotes: 1

Views: 5647

Answers (1)

Ashh
Ashh

Reputation: 46451

You need to loop through the ids array and convert them to mongoose 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 }}
])

Upvotes: 2

Related Questions