Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
getting an empty array for filter/search text in mongo db using Nodejs

I am trying out search functionality in mongo database using node js.my result array always empty. I shared my code here. Someone help me to find whats wrong. after searching I am getting an empty array [] in my console.

models/contact.js

var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
cid: String,
name: {type: String, index: true},
phon: Number,
contactwith:  {type: String, index: true}
 });
 module.exports = mongoose.model('Contact', ContactSchema);


   mongoose.model('Contact', ContactSchema).ensureIndexes(function(err) {
      if (err)
          console.log(err);
       else
          console.log('create contact index successfully');
     });

Controller/contact.js

 var mongoose = require('mongoose');
 var Contact = mongoose.model('Contact');

  var ContactController = function(app,mongoose){   
    app.post('/search',function(req,res){
    var query = req.body.searchbx;
    console.log(query);
    var dbsearch = Contact.find({$text: {$search: query}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}});
    console.log(dbsearch);

    Contact.find({$text: {$search: query }}, function (err, results){
        if(err){
            console.log(err);
        }
        if(results){
            console.log('in results')
            console.log(results)
            res.render("search",{results: results});
        }
    })

  });
 }
module.exports = ContactController;

in jade file

form(id="search-filter" method ="POST" action="/search")
input#search-bx(type='text', name='searchbx' placeholder="search here")
input(type="submit", value="Search")
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I hope you are the beginner to nodeJS. Welcome :)

You did lot of things except 2 main things that is important!

  1. You have used POST method for search action. As per HTTP Standards, you have to use GET or PATCH for search related actions

Please Read: http://restfulapi.net/http-methods/

  1. You have tried for text search. $text queries to work, mongodb needs to index the field with an text index. You want to do some one changes in your mongoose

    {fields: {type: [String], text: true}

REF: https://docs.mongodb.com/v3.2/core/index-text/

Here is the simple and clean code: you can do modification based on the sample

var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', {
    name : {type : String, unique: true,  text: true},
    location: {type: String}
});

Controller:
app.get('/api/todo/search/:searchKey', function (req, res) {
        var searchKey = req.params.searchKey;
        if (!searchKey) {
            return res.send({ reason: 'searchKey required' });
        }
        Todo.find({
            $text: { $search: searchKey }}, function(err, result) {
                if (err) {
                    res.status(500);
                    return res.send({ reason: err.toString() });
                } else if (result && result.reason) {
                    return res.status(400).send(result);
                }
                return res.status(200).send(result);
            });
    });

All the Best!!!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!