I need help. I'm using the command .find() in my web application (express JS and Node) but it doesn't work. I want to search with multiple words.
It's quite confusing because when I use the command $all, and I force two words (for exemple, salt or sugar), it works, but when I'm using variables it doesn't...
I'm attaching some images (the route itself and the function with its fetch):
Here the function with its fetch
Many thanks
CodePudding user response:
You have passed ingredientBucar1
and ingredientBucar2
with sign
it will become a single string. so You are passing 'sa1' and 'azucar' in ingredientBucar1 and ingredientBucar2, It will be passed to api as 'sa1' and 'azucar'
To overcome this You can pass it in post api and get in req.body
or you can pass it through search params or pass them through 2 different query params like
your_api_endpoint/:ingredientBucar1/:ingredientBucar2
CodePudding user response:
It's me, here is the code:
FUNCIONES.JS function buscarPorIngredientes(){
// let ingredienteABuscar01=document.getElementById("buscarIngrediente01","buscarIngrediente02","buscarIngrediente03","buscarIngrediente04","buscarIngrediente05").value;
let ingredienteABuscar1=document.getElementById("buscarIngrediente01").value;
let ingredienteABuscar2=document.getElementById("buscarIngrediente02").value;
fetch("/busquedaIngredientes/" ingredienteABuscar1 ingredienteABuscar2
)
.then(function(res){
return res.json();
},
)
.then(function(datos){
for (let i = 0; i < datos.length; i ){
document.getElementById("divBuscarPorIngrediente").innerHTML =
`<div>
<h4>${datos[i].nombre}</h4>
<p>INGREDIENTES: ${datos[i].ingredientes}</p>
<img src="${datos[i].imagen}" width="300"></a></p>
</div>`;
}
},
);
};
INDEX.JS
`app.get("/busquedaIngredientes/:ingredientes",buscarPorIngredientes2); function buscarPorIngredientes2(req,res){
const ingredienteABuscar1=req.params.ingredientes;
const ingredienteABuscar2=req.params.ingredientes;
app.locals.db.collection("cocteles").find({ingredientes: {$all: [
// ingredienteABuscar1,
// ingredienteABuscar2
"sal",
"azucar"
]}},
console.log(ingredienteABuscar2),
)
.toArray(
function(err,datos){
if(err!=null){
console.log(err);
}
else{
console.log(datos);
res.send(datos);
}
}
)
};`
CodePudding user response:
Thank you very much Srushti Shah. I am going to try this.