Figuring out how to best solve updating many fields based on nested ID with mongoose

Viewed 15

I have been looking around here for a bit now but I can't really find anything that really answered the question or problem I have so I'm giving it a go in asking. I have a function in my REST API that gives the user right to terminate his or her own membership. The thing is when the user does this, several other nested fields need to be updated. These fields are all nested in one object, which is the ownership object. The properties are owner, renter, and caretaker where the value is the ID of the user that is being removed. If the ID is in one of the fields it needs to be removed, and where the ID is might vary.

This is what I have done so far:

await Horse.updateMany(
    { 'ownership.owner': req.body.id },
    { 'ownership.owner': 'someAdminIDHere' },
);

await Horse.updateMany(
    { 'ownership.renter': req.body.id },
    { 'ownership.renter': null },
);

await Horse.updateMany(
    { 'ownership.caretaker': req.body.id },
    { 'ownership.caretaker': null },
);

But it feels really redundant and I was hoping to find a better way. I have been looking at populate and some other options but I am not really sure if they are the solution. Would very much appreciate some help here, even more so a clear description code example on how I might solve this with mongoose.

0 Answers
Related