Home > Software design >  Why its only updating the second item of the array?
Why its only updating the second item of the array?

Time:10-27

What im trying to do is to update one or more users with some data. I receive the user phone numbers in an array, exp: [" 1234555", " 1222222"]. I loop through them and I check if they exist or not. If they exist I update the data in the user model. The problem is that let's say I have two users to update. When I execute the function only the second user is updated, the first one is not.

exports.createNotifications= asyncHandler(async (req, res, next) => {
  const { userPhone, someData } = req.body;

  let createUserData;
  let updateUserData;
  let findUser;

  const createData = async () => {
    userPhone.map(async (phone) => {
      findUser = await Users.findOne({ phone: phone}).then(
        async (user) => {
          if (user) {
            updateUserData= await Users.findOneAndUpdate(
              { phone: phone},
              { $push: { someData : someData } },
              { new: true }
            );
          }
        }
      );
    });
  };

  await createNotifications();
  await new Promise((resolve) => setTimeout(resolve, 1000));
  console.log(updateUserData)


  res.status(200).json({
    success: true,
  });
});

How can I update both users?

CodePudding user response:

It fails because you dont wait for the async functions built in your 'map' (and actually you mess a lot with async, await and promises :p).

Considering that the code you shared is invalid, I assume that createData and createNotifications are the same.

You can wrap this creation into promises and wait for it to complete

const createNotifications = () => {
  return userPhone.map(async (phone) => {
    const user = await Users.findOne({ phone: phone})
    if (user) {
      await Users.findOneAndUpdate(
        { phone: phone},
        { $push: { someData : someData } },
        { new: true }
      )
    }
  })
}

Promise.all(createNotifications())
  .then(() => {
    res.status(200).json({
      success: true,
    })
  })

note: code not tested

CodePudding user response:

userPhone.map(phone => {
  let data = await Users.updateMany({
    phone
  }, {
    $push: {
      someData: someData
    }
  }, {
    new: true
  })
});
  • Related