Is this a good solution to when updating nested objects? #9872
Replies: 2 comments 1 reply
-
If you have a rapidly updating database, you could cause race conditions where multiple clients are updating the same code at once and end up with garbled objects if one user submits the change after another user has downloaded the object, but before his client has submitted it. For your situation , it is probally best to use Venue.Update() queries. See here in the mongoose docs. Sorry for replying so late to your post, i don't normally browse the discussions of here, you might find stack overflow will give you faster answer. (but they can tend to be rude at times as well) |
Beta Was this translation helpful? Give feedback.
-
That does work, but that seems to be too much repetition and that's an anti-pattern. try {
const venue = await Venue.findById(_id);
clean(req.body);
revenue.set(req.body);
await venue.save();
return res.send(venue);
} catch (err) {
res.send(err)
}
function clean(obj) {
for (const propName in obj) {
// technically, you'd need to do `!obj[propName]` to have the equivalent implementation
// of what you have in the original post
if (obj[propName] == null) {
delete obj[propName];
}
} Also, as @AndrewFriendTech has mentioned, you want to One more thing I'd do with the changes above is validate the |
Beta Was this translation helpful? Give feedback.
-
I've been struggling all evening with the issue where updating one key in a nested object causes all values to be overwritten. After loads of research looking for a simple solution, I tried something out where, as far as I understand it, any keys that don't receive a new value will update the new instance with the existing data.
It seems to work but am I missing something that could become an issue?
Beta Was this translation helpful? Give feedback.
All reactions