mongodbmongoosenodesrobo3t

mongoose Schema.index() not working


Using "mongoose": "4.13.6"

Im trying to do a full word search for firstName.

I have Schema

import mongoose from 'mongoose';

 let fbUserSchema = mongoose.Schema({
    _id :  mongoose.Schema.Types.ObjectId,
    facebookId : { type: String, required: true, index: true},
    gender : String,
    profileUrl : String,
    imageUrl : String,
    firstName : String,
    token : String,
    email : String
 });

 fbUserSchema.index({firstName: 'text'});
 const fbUser = module.exports = mongoose.model('fbUser', fbUserSchema);

I do a query

import fbUser from '../model/fbUser';

fbUser.find({ $text: { $search: 'Ann' } }, function(err, data) {
    if(err) throw err;
    console.log(data);
  });

This returns me

[]

But in my collection, I have a firstName as 'Anna' .

{
    "_id" : ObjectId("5a26d554677475818a795f75"),
    "facebookId" : "123456",
    "gender" : "Female",
    "profileUrl" : "https://www.facebook.com/asdfasf",
    "imageUrl" : "/img/profile/sm1.jpg",
    "firstName" : "Anna",
    "token" : "ldhajksdkjasdakjsdajksd",
    "email" : "sm1@gmail.com"
}

Solution

  • Mongoose text search does indeed search for the whole word. If you are trying to get a partial match of a string, you should use $regex instead:

    fbUser.find({ 
      firstName: {
        $regex: ""^.*Ann.*$"",
        $options: "i"
      } 
    }, function(err, data) {
      if(err) throw err;
      console.log(data);
    });