0

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"
}
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Sandeep Ranjan
  • 824
  • 15
  • 33
  • Possible duplicate of [mongoDB prefix wildcard: fulltext-search ($text) find part with search-string](https://stackoverflow.com/questions/24343156/mongodb-prefix-wildcard-fulltext-search-text-find-part-with-search-string) – dnickless Dec 13 '17 at 20:05
  • my ques is diff – Sandeep Ranjan Dec 17 '17 at 17:05

1 Answers1

1

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);
});
Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26