Search code examples
node.jssails.jssails-mongo

How to do Character wise Search with mongoDB Collection inside model in sails.js


I am newbie to sails and node.js. I am creating a Forum and want to add search function in order to search threads that match with User Search input. My search function need to character wise match the user entered characters with database thread's title. Is there any possible way to do that in sails ? Is it possible to use String distance in sails ? My models look like as follows,

Forum.js

attributes: {

  id: {
      type: 'string',
      primaryKey: true,
      unique: true
  },

  name: {
      type: 'string',
      required: true
  },

  threads: {
      collection: 'thread',
      via: 'threadOwner'
  }

},

Thread.js

attributes: {

    id: {
        type: 'string',
        primaryKey: true,
        unique: true
    },

    creatorUid: {
        type: 'string',
        required: true
    },

    title: {
        type: 'string',
        required: true
    },

    description: {
        type: 'string'
    },
    threadOwner: {
        model: 'forum'
    }

},

Solution

  • Try this,

        Thread.find({
            or : [
                {title : { contains:searchKey }},
                {description : { contains:searchKey }}
            ],
            threadOwner:forum
        }).exec(function(err,matched){
              //Your code... 
        })