1

I use migrate-mongo to run my migrations across dev/stage/prod environments. For my documents I use the autogenerated mongo id-s. But when I run an insertion script like this

let result = await db.collection("regions").insertMany(
[{
                region: "Asia",
                hostedIn: "Singapore",
                token: "asia",
                order:1
},

using migrate-mongo it generates different id-s for each environments. What is the best practice to keep ids the same across the environments?

Karen Avdalyan
  • 382
  • 1
  • 20

1 Answers1

0

To keep the same Id's you literally have to read the documents first, then insert them.

const existingDocs = await db.collection("regions").find({}).toArray();
let result = await db.collection("regions").insertMany(existingDocs)

Another option is to pre-generate those ids and then use them in your script.

let result = await db.collection("regions").insertMany(
[{
     region: "Asia",
     hostedIn: "Singapore",
     token: "asia",
     order:1,
     _id: 1
}]
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • Tom, I can't use the first approach you described because the dev and prod envs should have an access to each other, so I read from dev and write to prod which is not possible. Do I understand properly that the only solution is using pre-generated ids? – Karen Avdalyan Aug 03 '23 at 06:43
  • 1
    Yes, no other solution then. – Tom Slabbaert Aug 03 '23 at 07:22