I’m creating a project using the mern stack. I’m trying to update a project from my frontend to my backend. When I update it it will return success but when I check the database nothing is updated? I’m trying to update the product with the prodID that is entered in the frontend
This is my post route
router.post("/updateStock", (req, res) => {
const prodID = req.body.prodID
const product = new Product(req.body)
Product.findOneAndUpdate(prodID, { new: true }, {returnOriginal: false}, function(err, products) {
if (err) {
console.log("err", err);
res.status(500).send(err);
} else {
console.log("success");
res.send(product);
}
});
});
This is my schema
const mongoose = require("mongoose");
const Product = mongoose.model(
"Product",
new mongoose.Schema({
title: String,
manufacturer: String,
price: String,
catergory: String,
quantity: String,
prodID: String,
images: Array
})
);
module.exports = Product;
3
Answers
You are not passing the new updated body to
findOneAndUpdate
. ThefindOneAndUpdate
is expectingdb.collection.findOneAndUpdate( filter, update, options )
. The code should be like this:-Follow this Schema =>
Pass Update object
Following Mongoose Docs here
1st:
You added filter as a string, however it should’ve been an object like below
2nd:
no need to instantiate the Product schema, use the update object
3rd:
You used the same option, also
new:true
took the place of the update object4th:
Use promise not callbacks, however you have a typo in the callback you called
products
and you sentproduct