Recently I have finished Legacy Full-Stack course on FCC, and as a part of checking my skills I am trying to build a MERN platform. Currently I am at the point of building RESTful API connected to the MongoDB with Mongoose. Most of the routes are ready, but I am stuck for nearly two days on one seemingly simple thing. I have an array with reviews, nested 2 levels inside of a model. What I want to do is pass 3 parameters in the query, and use them to localize the object in the array and replace it’s content on PUT method. I have tried Model.updateOne method with $set
attribute, however this one overides the whole array and othe elements are gone, when I use $push
instead it add’s duplicated object. I have been looking for the answer pretty much everywhere but I am stuck. Below you can have a look at my code, and link to GItHub repo is also attached.
Thanks in advance!
exports.EditReview = async (req, res) => {
try {
const result = reviewSchema.validate(req.body);
if (result.error) {
console.log(result.error.message);
return res.json({
error: true,
status: 400,
message: result.error.message,
});
}
const tempCar = await Car.updateOne(
{
make: req.params.make,
models: {
$elemMatch: {
name: req.params.model,
"models.$.reviews._id": req.params._id,
},
},
// "models.name": req.params.model,
// "reviews._id": req.params._id,
},
{ $set: { "models.$.reviews": result.value } }
);
console.log(tempCar);
return res.status(200).json({
success: true,
message: "Review added to the DB",
});
} catch (error) {}
console.error(error);
return res.status(500).json({
error: true,
message: "Cannot add the car review",
});
};
https://github.com/KowalewskiPawel/reviwIT-Server/blob/main/cars/car.controller.js