Search code examples
mongodbexpressmongooseuuid

Update all documents adding new fields with different values


I'm using uuid package in express app now I need add those ids to all my document.

Users.updateMany({},{$set:{newId:uuid()}},(err,success)=>{
      if(success) console.log(success);
});

I tried this way,success returns with different values,but in database it saves with same value.I need to add that newId field in my documents with different ids thats all.Thanks for attention and for help!!


Solution

  • If you are familiar with async/await this should work

    async function updateUuid() {
      try {
        const users = await Users.find({});
        for (const user of users) {
          const uuid = uuid();
          await User.findByIdAndUpdate(user._id, { $set: { newId: uuid } });
        }
      } catch (e) {
        console.error(e);
      }
    }