0
I have a question about giving update
using Mongoose. I already have the route done and working, only I’m having a problem.
So I’ve unstructured all the data I’m going to take from req.body
, then when I pass all the data already filled to do update
, goes normal, only in case I passed some data null
, it replaces the field by null
.
After researching the doc of Mongoose, I found the option omitUndefined
, excluding fields undefined
of update
, only usually when we pass him blank he comes null
and not undefined
.
Taking the two images below as an example, passing and not passing the blank field.
Passing the name
and desc
, and replacing normal
Now moving on to desc
as null
, and within the database overwriting the content by null
.
And as you can see, the price
and the status
remain the same, because as they do not pass in the req.body
, they come as undefined
.
Could someone give me a hand?
Solution found
After receiving help in the post answers, I was able to solve the problem with the solution below using Mongoose
async update(req: Request, res: Response) {
try {
const { id } = req.params;
const { name, description, price, status, category } = req.body;
await product.find(
{ _id: id },
async function (err, [data]: IProductProps[]) {
if (!err) {
const response = await product.findByIdAndUpdate(
{ _id: id },
{
$set: {
name: name || data.name,
description: description || data.description,
price: price || data.price,
status: status || data.status,
category: category || data.category,
},
},
{
new: true,
}
);
return res.json(response);
}
}
);
} catch {
return res.status(400).json({ error: "error for updating a product" });
}
},
Got a little confused! You don’t want to save data
null
in the bank, is that it? If it is that, it would not be better to define in the model that such a field does not acceptnull
? And from what you wrote, you understand""
(empty string) likenull
?– Cmte Cardeal
Thanks for the answer, that, I do not want to save null in mongodb, I searched and does not have a property for example noNullable, there is a required property that makes it mandatory. But even with this property it accepts null in the fields.
– kissinger156