Quiero buscar un elemento específico de la base de datos (mongodb) usando mongoose ODM y mostrar el elemento en mi vista. Esto es lo que he encontrado en Internet, pero no funciona. Aquí está mi controlador:
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); }); }Cuando ejecuto mi servidor, aparece este error después de intentar buscar:
CastError: la conversión a ObjectId falló para el valor "buscar" (tipo de cadena) en la ruta "_id" para el modelo "Producto"
Aquí está mi formulario de búsqueda:
<form action="/products" method="POST"> <input type="text" placeholder="search product" name="name"> <button type="submit">Search</button> </form>Muestra de los campos en mi 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: 0Esquema de mi producto:
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 } });utilizar este
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); }); }Porque estaba haciendo una solicitud de publicación y pasando datos de formulario (título) para ser filtrados; Debería haber usado req.body . Este controlador funcionó:
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); }); }