What can you do?
const obj = {
"name":val
}
// to
const prop = "name";
const obj = {
[prop]:val
}
With new javaScript
, you can create object by assigning dynamic properties to it.
Use Case
You have following document in your MongoDB
collection
{
name:"Rahul kumar",
title:"....",
body:"..",
tags:[...],
date:"..",
createdAt:"...",
editedAt:"..",
....more
}
If you know MongoDB
then you might have modified any attribute of document
.
In this case, we need to write query like below,
db.collection.update({...filter},{
$set:{
attributeName:"value...",
// like
title:"....",
}
});
If you are not using dynamic property feature, then you might be creating different express routes and different functions to edit name, title, body and so on..
But, do you know you can do this in just single function?
Yeah, here we can use dynamic property names..
function update(attr,data){
db.collection.update({...filter},{
$set:{
[attr]:data
}
});
}
Now, you can pass any string as attribute name and data to edit the value.
There might be more use cases which you can comment below.
Top comments (0)