0

So I have this kind-a-like schema at the moment

user:{ _id: string,
       shifts:[_id:string],
       name: ... ,
       ...
}

And now I want to delete a shift._id from all my users who have this.

I allready have an array of all the users their id's who have this shift._id.

I've tried this, with shift_id as the id of the shift i want to delete:

userIdArray.forEach(user_id => {
    UserSchema.update({_id: user_id}, {$pull: {shifts: shift_id} });
  });

and got the error:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)

Can somebody explain me what I did wrong?

Edit:

So what i did was, i called a function named:

function deleteShiftIdInUsers(users, shift_id){ 
users.forEach(user_id => {
    UserSchema.update({_id: user_id}, {$pull: {shifts: shift_id} });
  });}

and called this function in my async (req, res, next) route.

Now i just execute this code within the async function instead doing it like code...; deleteShiftIdInUsers(users, shift_id); res.status(200).json(...);

still new to js, so what did i do wrong?

Gleb S
  • 34
  • 7
  • The error you mentioned is not of MongoDB check this answer - https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – Puneet Singh May 14 '20 at 13:11
  • @PuneetSingh, Can you help me maybe? So if you read the edit, you can see that my logic was of... do you know where or what? – Gleb S May 14 '20 at 13:35
  • You still calling your query in loop in code don't do that, use update many, and use with asun/await await – Puneet Singh May 16 '20 at 00:40

1 Answers1

0

I think, You need to call the mongoose function with async/await, you should use updateMany with $in instead of looping for user_id

var ObjectId = require("mongoose").Types.ObjectId

async function deleteShiftIdInUsers(users, shift_id){ 
  users = users.map(user_id => ObjectId(user_id))
  return await UserSchema.updateMany({"_id": {"$in": users}}, {"$pull": {"shifts": ObjectId(shift_id)} });
}

when you are calling this function

await deleteShiftIdInUsers(users, shift_id);
res.status(200).json(...);
Puneet Singh
  • 3,477
  • 1
  • 26
  • 39