Home > Software design >  mongoose update mutiple users array
mongoose update mutiple users array

Time:08-29

I have an array that has user's ids

array like this ["userid1","userid2","userid3"]

this array could have many user's id or just one. just random.

I'm just trying to update user's datas

if the array has 5 user's ids it's supposed to update 5 user's datas

here's what I did

  const { mentionUsers, sender, notificationType, image } = req.body;
  console.log(mentionUsers, sender, notificationType, image);
  try {
    if (mentionUsers.length === 0)
      return res.status(204).json({ message: "no mention users" });

    mentionUsers.map(async (userId) => {
      let notification = {
        _id: new mongoose.Types.ObjectId(),
        sender,
        notificationType,
        image,
        read: false,
      };
      let user = await User.findByIdAndUpdate(
        userId,
        { $push: { notifications: notification } },
        { new: true }
      );
      console.log(user);
    });

it doesn't update user's data

how can I update datas? thanks for reading my question

CodePudding user response:

You can update multiple documents at a time.

let notification = {
    _id: new mongoose.Types.ObjectId(),
    sender,
    notificationType,
    image,
    read: false
};

User.update(
    { _id: { $in: mentionUsers } },
    { $push: { notifications: notification } },
    { new: true }
);
  • Related