M
M
Mikhailo Poberezhny2016-10-04 22:30:16
Node.js
Mikhailo Poberezhny, 2016-10-04 22:30:16

How to do an index search in Mongoose?

You need to do a full-text search on the table (mongoDB).
Went to off documentation.
Here is the diagram:

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({
  tags: [],
  text: { type: String }
});

testSchema.index({text: 'text', tags: 'text'});
module.exports = mongoose.model('Test', testSchema);

Search code:
var test = require('../models/Test.js');

  test
    .find({ $text : { $search : "random" } })
    .exec(function(err, results) {
      if (err) return res.send(err);
      res.send(results)
    });

Objects from the base:
{ 
    "_id" : ObjectId("57f3d21358b045bc1f16a156"), 
    "text" : "random 1", 
    "tags" : [ "a", "b", "c" ]
}
{ 
    "_id" : ObjectId("57f3d2a858b045bc1f16a157"), 
    "text" : "test str 2", 
    "tags" : [ "d",   "e",  "f" ]
}
{ 
    "_id" : ObjectId("57f3d2b758b045bc1f16a158"), 
    "text" : "random 2", 
    "tags" : [ "a",  "e",  "f" ]
}

The problem is that the result comes: an empty array []
Tell me where I made a mistake or throw off an example of a working code, if any. (you can’t use elastic or sphinx so they said to do it on mong)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question