Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Search an item with mongoose

I want to search for a specific item from the database(mongodb) using mongoose ODM and display the item in my view. This is what I have found from the internet but its not working. Here is my controller:

exports.getSearch = (req, res, next) => { 
  const { name } = req.query;
  Product.find({title: { $regex: name, $options: "i" }})
    .then(title  => {
      res.render('shop/product-list', {
        prods:  title ,
        pageTitle: 'All Products',
        path: '/products'  
      });
    })
    .catch(err => {
      console.log(err);
    });
}

When I run my server I get this error after trying to search:

CastError: Cast to ObjectId failed for value "search" (type string) at path "_id" for model "Product"

Here is my search form:

<form action="/products" method="POST">
                    <input type="text" placeholder="search product" name="name">
                    <button type="submit">Search</button>
                </form>

Sample of the fields in my mongodb:

_id: 628398cb487a2cf1538c4087
title: "Dell  E7240"
price: 28600
description: "Dell Latitude E7240
Core i5 4th gen
12'
4GB RAM 
120GB SSD"
imageUrl: "images/2022-05-17T12:44:58.743Z-e7250.jpg"
userId: 627540c6672b6ab4007a3856
__v: 0

My product Schema:

const productSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  imageUrl: {
    type: String,
    required: true
  },
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
});
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

use this

  exports.getSearch = (req, res, next) => { 
      const { title } = req.query;
      Product.find({title: { $regex: title, $options: "i" }})
        .then(prodName  => {
          res.render('shop/product-list', {
            prods:  prodName ,
            pageTitle: 'All Products',
            path: '/products'  
          });
        })
        .catch(err => {
          console.log(err);
        });
    }
over 4 years ago · Santiago Trujillo Relatório

0

Because I was doing a post request and passing form data(title) to be filtered; I ought to have used req.body. This controller worked:

exports.getSearch = (req, res, next) => { 
    const title = req.body.title;
    Product.find({ title: { $regex: title, $options: "i" } })
        .then(title => {
            res.render('shop/index', {
            prods:  title ,
            pageTitle: 'All Products',
            path: '/products'  
            });
        })
        .catch(err => {
          console.log(err);
        });
    }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda