I am coding along with some MongoDB tutorial. I came across this.
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
What exactly is $set? I think it is used to set anything from req.body
to the DB, but I want to see some documentation about it and other $
use cases. However, I cannot find any documentation about $set
.
CodePudding user response:
The $set operator replaces the value of a field with the specified value.
This means that when u update some data, u can set the values of specific fields, even if those fields do not exist yet.
Here is all information u need: https://docs.mongodb.com/manual/reference/operator/update/set/
"If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field."