Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda