Home > Net >  How can I delete a document automatically when its field's value equals zero in node.js with mo
How can I delete a document automatically when its field's value equals zero in node.js with mo

Time:12-24

I have a Product Collection and it has several fields. One of them is "productQuantity", which keeps the number of that product and it looks like that:

const ProductSchema = new Schema({
  productName: {
    type: String,
    unique: true,
    required: true,
  },
  productBrand: {
    type: String,
    required: true,
  },
  productPrice: {
    type: String,
    required: true,
  },
  productPhoto: {
    type: String,
    required: true,
  },
  productQuantity: {
    type: Number,
    required: true,
  },
  slug: {
    type: String,
    unique: true,
  },
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
  },
});

For Example, I give 10 for productQuantity and now I have 10 products of it.

And I have page that I can purchase that product and it looks like that:

enter image description here

The HTML Code Of this page:

<div style="display:flex; justify-content: center;">
            <div style="border: 2px solid black;">
                <img style="width: 465.16px;" src="<%= productCard.productPhoto %>">
            </div>
            <div  style="border: 2px solid black; display: flex; flex-direction: column;">
                <div style="margin:30px;">
                    <%= productCard.productName %>
                </div>
                <div style="margin:30px;">
                  <%= productCard.productBrand %>
                </div>

                <ul  style="margin:30px; list-style-type: none; padding: 0px;">
                    <li style="margin-bottom: 7px;">Kategori: <%= productCard.category.categoryName %>  </li>
                    <li style="margin-bottom: 7px;">Marka: <%= productCard.productBrand %></li>
                    <li style="margin-bottom: 7px;">Garanti Süresi: 24 Ay</li>
                </ul>

                <form method="POST" action="/product/<%= productCard._id %>?_method=PUT" style="display:flex; align-items: center;" novalidate>
                    <div style="display: flex; border: 2px solid black; margin:30px; border-radius: 20px; overflow: hidden;">
                       <a id="azalt" style="text-decoration: none; color: black; background-color: antiquewhite; padding: 0px 10px;" href="javascript:void(0)"><i ></i></a>
                        <input id="Quantity" style="text-align: center; width:100px;" type="text" value="1" name="quantity">
                        <a id="arttır" style="text-decoration: none; color: black; background-color: antiquewhite; padding: 0px 10px;" href="javascript:void(0)"><i ></i></a>
                    </div>
                
                <button type="submit" style=" margin-right: 20px; width: 200px; height:50px; background-color: green; color: aliceblue; font-weight: 900;">
                    SATIN AL
                </button>
              </form>

            </div>
            
        </div>

When I click the green button it purchases the number of products according to the number next to it.

The Route

router.route('/:id').put(productController.buyProduct);

And the controller

exports.buyProduct = async (req,res) =>{
    let boughtItemQuantity = req.body.quantity;
    const product = await Product.findById(req.params.id);

    product.productQuantity = product.productQuantity - boughtItemQuantity;

    product.save();

    res.status(200).redirect("/")

}

When the work is done it redirects the user to the main page where the products gets listed. So what I want to do is when I have ten products and one user buys 10 products of these products I want that product's document to get deleted so it doesn't appear on the main page.

I tried

exports.buyProduct = async (req,res) =>{
    let boughtItemQuantity = req.body.quantity;
    const product = await Product.findById(req.params.id);

    product.productQuantity = product.productQuantity - boughtItemQuantity;

    product.save();

    if(product.productQuantity == 0) 
   {
     await findByIdAndRemove(req.params.id)
   }

    res.status(200).redirect("/")

}

But I guess I can't update and delete in the same controller because it deleted the document but it didn't redirect me to the main page. So basically it didn't work

So I don't how to achieve that, should I write a middleware or something different?

Thanks in advance.

CodePudding user response:

You should await the save() function which returns a Promise.
Also, you should write Product.findByIdAndRemove:

exports.buyProduct = async (req, res) => {
  let boughtItemQuantity = req.body.quantity;

  const product = await Product.findById(req.params.id);

  product.productQuantity = product.productQuantity - boughtItemQuantity;

  await product.save();

  if (product.productQuantity <= 0) {
    await Product.findByIdAndRemove(req.params.id);
  }

  res.status(200).redirect('/');
};
  • Related