Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

node.js - How to filter mongoDB in NodeJS API, checking if values are included in objects in array

I am writing REST API in NodeJS with MongoDB. Structure of the database is:

[
    {
        "_id": "12345",
        "name": "Meal name",
        "category": "dessert",
        "area": "british",
        "imageUrl": "https.image.jpg",
        "instructions": "some instructions...",
        "ingredients": [
            {
                "name": "salt",
                "measure": "1g"
            },
            {
                "name": "chicken",
                "measure": "1"
            },
            {
                "name": "butter",
                "measure": "90g"
            }, ...
        ]
    }, ...
]

I can write a route to get data which meet one condition, i.e.:

//getting all, when category = :category
router.get('/meals/category=:category', async (req, res) => {
  try {
    const meals = await Meal.find({category: req.params.category})
    res.json(meals)

  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

Here, route

'meals/category=vegetarian'

get all data with category = vegetarian.

However, I want to have route, which will filter all data by parameters: category, area, ingredients. For example:

meals/ingredients=salt,pepper&category=dessert&area=american

should return all data, which contains salt and pepper in array, and category = dessert.

another example:

meals/area=american&category=dessert

should return all data, where area=american and category=dessert

How can I write the router.get() method to achieve that?

question from:https://stackoverflow.com/questions/65911521/how-to-filter-mongodb-in-nodejs-api-checking-if-values-are-included-in-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...