DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Mongoose dynamic update hack
Rubin
Rubin

Posted on

Mongoose dynamic update hack

Why do you use mongoose you say?
Let’s face it, writing MongoDB validation, casting and business logic boilerplate is a drag. Mongoose eases the whole mess.
While working with mongoose specially on the update operation , you will notice that you will have to provide the selector for the document you are modifying (normally _id or username ) along with the fields you wish to modify and their corresponding values that you would like to update.
Here is a simple snippet to summarize the whole thought above

User.update({
"username": req.params.user} , {$set:
{age: req.body.age, location: req.body.location, name:req.body.name ....}
} ,
function (err , success) {
if (err) throw (err);
else {
res.send({
msg: 'update success'
})
}})
Enter fullscreen mode Exit fullscreen mode

The code is okay if you are to update two to handful of fields but its get kinda ugly as the field to be updated gets increased. Say 100 fields . Also if you do manage to write the update query for 100 fields , whats the chance that the properties names in the schema will remain the same forever. If the schema were to update, you will be writing 100+100 = 200 update assignments.
This is where my code comes to rescue. Not only it dynamically populates the update fields on the query , it also picks up the field name from the request.

const entries = Object.keys(req.body)
const updates = {}

// constructing dynamic query

for (let i = 0; i < entries.length; i++) {
updates[entries[i]] = Object.values(req.body)[i]
}
User.update({
"username": req.params.user
} , {
$set: updates
} ,
function (err , success) {
if (err) throw (err);
else {
res.send({
msg: "update success"
})
}
}

Enter fullscreen mode Exit fullscreen mode

Happy Node'ing

Beerpay

Top comments (6)

Collapse
 
phatdang profile image
PHAT DANG MINH

Thanks!

Collapse
 
rudolphh profile image
Rudy A. Hernandez

can't we just use

{ $set: req.body }
Enter fullscreen mode Exit fullscreen mode

???

Collapse
 
idlevandal profile image
David Allen

Awesome.. Thank you.. πŸ₯‡

Collapse
 
rubiin profile image
Rubin

anytime

Collapse
 
ihssan_89 profile image
Ehsan Atassi

Awesome THnaks

Collapse
 
_ahmedta profile image
ahmed tawfik

Nice
I was searching for such solution .. thanks for sharing

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout πŸ˜†