【问题标题】:Fetching data from MongoDB with some conditional statements in the backend在后端使用一些条件语句从 MongoDB 获取数据
【发布时间】:2021-08-10 17:34:17
【问题描述】:

以下代码从 MongoDB 中获取所有数据(此处为产品)并将其发送到前端。 我想通过引入一些条件(if else 语句)来改变这一点,并且只有那些满足该条件的产品才应该从数据库中获取。

const getProducts = asyncHandler(async (req, res) => {
  const pageSize = 10
  const page = Number(req.query.pageNumber) || 1

  const keyword = req.query.keyword
    ? {
        name: {
          $regex: req.query.keyword,
          $options: 'i',
        },
      }
    : {}

  const count = await Product.countDocuments({ ...keyword })
  const products = await Product.find({ ...keyword })
    .limit(pageSize)
    .skip(pageSize * (page - 1))

  res.json({ products, page, pages: Math.ceil(count / pageSize) })
})

【问题讨论】:

    标签: node.js mongodb express frontend backend


    【解决方案1】:

    您可以使用大量 MongoDB 运算符根据您的条件查找数据。以下是一些您可以尝试的运算符:https://docs.mongodb.com/manual/reference/operator/query/

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 1970-01-01
      • 2020-02-20
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2018-06-29
      相关资源
      最近更新 更多