Home > Back-end >  why is findOneAndUpdate not updating in the DB?
why is findOneAndUpdate not updating in the DB?

Time:05-08

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;

CodePudding user response:

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);
})

CodePudding user response:

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 prodID = req.body.prodID

    const product = new Product(req.body)

    Product.findOneAndUpdate(prodID, 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);
        }
    });

CodePudding user response:

Follow this Schema => db.collection.findOneAndUpdate( filter, update, options ) Pass Update object

  • Related