skip to Main Content

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


  1. You are not passing the new updated body to findOneAndUpdate. The findOneAndUpdate is expecting db.collection.findOneAndUpdate( filter, update, options ). The code should be like this:-

        router.post("/updateStock", (req, res) => {
    
        const product = new Product(req.body);
        const filter = {prodID: req.body.prodID}
    
        Product.findOneAndUpdate(filter, product, { 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);
            }
        });
    
    Login or Signup to reply.
  2. Follow this Schema =>

    db.collection.findOneAndUpdate(filter, update, options)
    

    Pass Update object

    Login or Signup to reply.
  3. Following Mongoose Docs here

    1st:

    You added filter as a string, however it should’ve been an object like below

    const filter = {prodID: req.body.prodID}
    

    2nd:

    no need to instantiate the Product schema, use the update object

    const update = req.body
    

    3rd:
    You used the same option, also new:true took the place of the update object

    returnOriginal: false is equivalent to new: true

    4th:

    Use promise not callbacks, however you have a typo in the callback you called products and you sent product

    Product.findOneAndUpdate(filter, update, {new: true}).then((product) => {
          console.log("success");
          res.send(product);
    }).catch(err => {
         console.log("err", err);
         res.status(500).send(err);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search