im using nodejs and mongoose to build an api, im trying to do the search feature, but it deosnt seem to query anything, the code.
app.get('/search', function(req,res){
return Questions.find({text: "noodles"}, function(err,q){
return res.send(q);
});
});
its not giving me any results, i know thier should be at least 4 results from this query, thiers 4 documents in the questions database with the word "noodles", everything is working the the database connection and my node server
We have also looked at how to establish a database connection and how to create a schema for our collections. Mongoose can be used to connect to both MongoDB and MongoDB Atlas to your Node.js app. I hope you found this article helpful.
Node.js Mongoose.js connects your MongoDB clusters or collections with your Node.js app. It enables you to create schemas for your documents. Mongoose provides a lot of functionality when creating and working with schemas.
If you're trying to create an API to search mongoDB collection based on title i.e; a text field try implementing text search feature of mongoDB : text search in mongoDB , Just create a text index on title field & then create an API with post method which takes in parameter that can be queried against title field.
Mongoose has a very simple Model.find function for MongoDB queries in Node.js, as shown below. In this case the model is Comment, as defined using the var statement near the end.
What your query is doing is finding documents where the text
property matches "noodles"
exactly. Assuming you're trying to query for documents where the text
property simply contains "noodles"
somewhere, you should use a regular expression instead:
app.get('/search', function(req,res){
var regex = new RegExp('noodles', 'i'); // 'i' makes it case insensitive
return Questions.find({text: regex}, function(err,q){
return res.send(q);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With