S
S
Sanchik972020-08-06 12:42:20
MongoDB
Sanchik97, 2020-08-06 12:42:20

How to find object by field in mongodb?

Good afternoon! How can you have a query by which you need to find an object in the product model:

The code

module.exports.getById = function (req, res) {
    Product.findOne({ url: req.params.url }, (err, doc) => {
        if (err) {
            return errorHandler(res, 404, 'Ошибка! Товар не найден', err)
        }

       res.status(200).send(doc)
    })
}


When selecting by _id, if it does not find a product in the database, it returns a 404 error. If it is selected by the url field, then it returns null and works further. How can I get rid of this behavior and return a 404 error?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-08-06
@Sanchik97

module.exports.getById = async function (req, res) {
  try {
    const product = await Product.findOne({ url: req.params.url })
    if (!product) {
      throw new Error()
    } 
  catch {
    return errorHandler(res, 404, 'Ошибка! Товар не найден', err)
  }
}

P
Pavel Didenko, 2020-08-06
@Dasslier

if (err || !doc) ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question