How to replace a string in JSON Array using mongoose

Viewed 180

I need to remove the domain name from the URL in the JSON array stored in Mongo DB using Mongoose.

JSON Array format in DB

{
  "_id": {
    "$oid": "602a482223df2a16e26f51bc"
  },
  "message": "Test Again",
  "pollType": {
    "$numberInt": "1"
  },
  "type": "TEST",
  "optionList": [
    {
      "name": "name",
      "original": "https://name/test/pictures/1613383695668-71393-0d1f829222f945dc",
      "thumbnail": "https://name/test/pictures/1613383695668-71393-0d1f829222f945dc",
      "vote": {
        "$numberInt": "1"
      },
      "_id": {
        "$oid": "602a482223df2a16e26f51b9"
      },
      "participateUser": [
        {
          "$oid": "5c9baa00bcafa608891b0b44"
        }
      ],
      "latestParticipate": [
        {
          "$oid": "5c9baa00bcafa608891b0b44"
        }
      ]
    },
    {
      "name": null,
      "original": "https://name/test/pictures/1613383695672-71393-e92a34eaf6b48b19",
      "thumbnail": "https://name/test/pictures/1613383695672-71393-e92a34eaf6b48b19",
      "vote": {
        "$numberInt": "0"
      },
      "_id": {
        "$oid": "602a482223df2a16e26f51ba"
      },
      "participateUser": [
        
      ]
    },
    {
      "name": null,
      "original": "https://name/test/pictures/1613383695630-71393-3387191491ba279c",
      "thumbnail": "https://name/test/pictures/1613383695630-71393-3387191491ba279c",
      "vote": {
        "$numberInt": "0"
      },
      "_id": {
        "$oid": "602a482223df2a16e26f51bb"
      },
      "participateUser": [
        
      ]
    }
  ],
  "pollId": {
    "$oid": "602a482223df2a16e26f51b8"
  },
  "createdAt": {
    "$date": {
      "$numberLong": "1613383714396"
    }
  },
  "updatedAt": {
    "$date": {
      "$numberLong": "1613383714396"
    }
  },
  "totalVoteCount": {
    "$numberInt": "1"
  },
  "participateUser": [
    {
      "$oid": "5c9baa00bcafa608891b0b44"
    }
  ]
}

I am using below code to replace a string

return new Promise(async (resolve, reject) => {
        console.log("Iam called")
        MongoClient.connect('mongoDBconfig', function (err, client) {
            if (err) throw err;

            var collection = "test"

            var db = client.db('testDB');
            db.collection(collection).updateMany({
                "optionList.thumbnail": { $regex: /name/ },
            }, {
                "$set": {    

                    "optionList.$.thumbnail": {
                        $replaceOne: { input: "optionList.$.thumbnail", find: "https://name/test", replacement: "" },

                    }

                    }
                }
            }, function (error, success) {
                if (success) {
                    resolve(success)

                }
                else {
                    reject(error)
                }
            })
        })
    })

but when I call this function I getting below error

DB Error : Duplicate Entry : dollar ($) prefixed field '$replaceOne' in 'optionList.0.original.$replaceOne' is not valid for storage.

1 Answers

The $replaceOne is a aggregation operator starting from MongoDB v4.4, you can use update with aggregation pipeline starting from MongoDB v4.2

  • $map to iterate loop of optionList array
  • $replaceOne to replace string
  • $mergeObjects to merge current object with updated original field
let originalName = "https://name/test";
db.collection(collection).updateMany(
  { "optionList.original": { $regex: originalName } },
  [{
    $set: {
      optionList: {
        $map: {
          input: "$optionList",
          in: {
            $mergeObjects: [
              "$$this",
              {
                thumbnail: {
                  $replaceOne: {
                    input: "$$this.thumbnail",
                    find: originalName,
                    replacement: ""
                  }
                }
              }
            ]
          }
        }
      }
    }
  }],
  function (error, success) {
    if (success) { resolve(success) }
    else { reject(error) }
  }
)

Playground

Related