Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching database with mongoose api and nodejs?

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

like image 745
user1551482 Avatar asked Aug 15 '12 20:08

user1551482


People also ask

Can I connect mongoose or MongoDB to my NodeJS app?

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.

What is node mongoose used for?

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.

How to create an API to search MongoDB collection based on title?

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.

How do I find the model of a MongoDB query in node?

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.


1 Answers

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);
    });
});
like image 67
JohnnyHK Avatar answered Oct 28 '22 00:10

JohnnyHK