0

I'm using mongo with node js & want to get the data for full-text search. But currently getting an empty array [] in return.

My API request is as follows -

router.post('/products/search', function(req, res, next) { 
    var search=req.body.search;
    console.log(search)
    Product.find({$text:{$search:search}},function(err,data)
    {
        console.log(data)
        res.send(data)  
    });
});

And the database code is as follows -

var ProductSchema = new Schema({
    category: String,
    name: String,
    price: Number,
    cover: String,
    search:String
})

Please help me to get the data.

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
vigin vp
  • 1
  • 3
  • Did you add the indexes properly? – Blue Nov 30 '18 at 08:18
  • yes[ { "_id": "5bfe79422005130af1da85e8", "category": "Clothing", "name": "Gorgeous Rubber Keyboard", "price": 50, "cover": "http://lorempixel.com/640/480/fashion", "__v": 0 }] – vigin vp Nov 30 '18 at 08:27
  • JonhnyHK's answer here https://stackoverflow.com/questions/28775051/best-way-to-perform-a-full-text-search-in-mongodb-and-mongoose should help point you in the right direction. – WillyMilimo Nov 30 '18 at 09:42

3 Answers3

0

Try to search As below.

db.products.createIndex( { search: "text" } )

router.post('/products/search', (req, res, next) => { 
    const search = req.body.search;
    Product.find({ $text: { $search: search } }).then(data => {
        console.log(data)
        res.json(data)  
    }).catch(err => {
        res.status(400).json(err.message)
    });
});

If you want to search using regex.

router.post('/products/search', (req, res, next) => { 
    const search = new Regex(req.body.search, i);
    Product.find({
        $or [
            {category: search}, 
            {name: search}, 
            {cover: search},
            {price: search}, 
            {search: search}
        ]
    }).then(data => {
        console.log(data)
        res.json(data)  
    }).catch(err => {
        res.status(400).json(err.message)
    });
});

Or If you want to search only on search field

router.post('/products/search', (req, res, next) => { 
    const search = new Regex(req.body.search, i);
    Product.find({search: search}).then(data => {
        console.log(data)
        res.json(data)  
    }).catch(err => {
        res.status(400).json(err.message)
    });
});
Nitish Thakrar
  • 515
  • 4
  • 16
0

Search using regex This way, It's works.

const searchText= "mail";
await EmailModel.find({
      $or: [{text: {$regex: searchText}}, {subject: {$regex: searchText}}, {from: {$regex: searchText}}]
    })

Take a look this link

Talha Noyon
  • 824
  • 7
  • 13
-1

you also need to create the text schema for it to work. in your case:

ProductSchema .index({   
    category: 'text',
    name: 'text, 
});
imixtron
  • 183
  • 10
  • I did the same what you told to do. But still, the issue is there. Could you check whether that is working in yours or not? – vigin vp Nov 30 '18 at 09:11