0

Is it possible to copy a documents _id to a new field as a string using mongoose-migrate?

async function up() {
   await this('guides').updateMany({}, { '$set': {slug: '$_id'}}, {multi: true});
}

This is just ends up setting the field to the string '$_id' instead of the string value of the id. The schema of slug requires it to be a string rather than an objectId

  • Does this answer your question? [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – Đăng Khoa Đinh Jun 11 '21 at 05:19

1 Answers1

0

Check this out:

await this('guides').aggregate([
  {
    "$set": {
      "slug": {
        "$concat": [
          {
            "$toString": "$_id"
          }
        ]
      }
    }
  }
])

Edit:

You can test it in mongoDB playground

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27