Skip to content

Instantly share code, notes, and snippets.

@oprearocks
Last active June 9, 2017 22:38
Show Gist options
  • Save oprearocks/f9d0d4f178b735a3351bb5475120d8ee to your computer and use it in GitHub Desktop.
Save oprearocks/f9d0d4f178b735a3351bb5475120d8ee to your computer and use it in GitHub Desktop.
A simpler way to update Mongodb documents
app.put('/user/:userId', (req, res) => {
User.findById(req.params.userId, (queryFailedError, user) => {
if (queryFailedError) {
res
.status(500)
.json({
errors: [queryFailedError]
});
}
if (!user) {
res
.status(404)
.json({
errors: ['Record not found']
});
}
// Copy all new properties from req.body.data to our user object
// Any property on user whose value differs from req.body.data will be updated
Object.assign(user, req.body.data);
user.save((saveError) => {
if (saveError) {
res
.status(500)
.json({
errors: [saveError]
});
}
res
.status(204)
.json({
success: true
});
})
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment