当文档的字段值在 node.js 中使用 mongoose 等于零时,如何自动删除文档?

How can I delete a document automatically when its field's value equals zero in node.js with mongoose?

提问人:Alim Gölcük 提问时间:12/24/2022 更新时间:12/24/2022 访问量:78

问:

我有一个产品集合,它有几个字段。其中之一是“productQuantity”,它保留了该产品的数量,如下所示:

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

例如,我为 productQuantity 提供了 10,现在我有 10 个产品。

我有页面可以购买该产品,它看起来像这样:

enter image description here

本页的HTML代码:

<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 class="icon-minus"></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 class="icon-plus"></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>

当我单击绿色按钮时,它会根据旁边的数字购买产品数量。

路线

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

和控制器

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("/")

}

工作完成后,它会将用户重定向到列出产品的主页。所以我想做的是,当我有 10 个产品并且一个用户购买了这些产品的 10 个产品时,我希望删除该产品的文档,这样它就不会出现在主页上。

我试过了

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("/")

}

但我想我不能在同一个控制器中更新和删除,因为它删除了文档,但它没有将我重定向到主页。所以基本上它没有用

所以我不知道如何实现这一点,我应该写一个中间件还是其他东西?

提前致谢。

JavaScript 节点.js MongoDB Mongoose 中间件

评论

0赞 Peter Thoeny 12/24/2022
在等待后执行重定向:if(product.productQuantity == 0) { await findByIdAndRemove(req.params.id); res.status(200).redirect("/") } { else res.status(200).redirect("/") }
3赞 Peter Thoeny 12/24/2022
另外,为什么不删除产品,为什么不查询数量为非零的产品呢?
0赞 Alim Gölcük 12/24/2022
是的,你是对的。我是一个新手,我什至没有想到它。@PeterSmith

答:

1赞 lpizzinidev 12/24/2022 #1

您应该使用返回 .
另外,你应该写:
awaitsave()PromiseProduct.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('/');
};