I am trying out search functionality in mongo database using node js.my result array always empty. I shared my code here. Someone help me to find whats wrong. after searching I am getting an empty array [] in my console.
models/contact.js
var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
cid: String,
name: {type: String, index: true},
phon: Number,
contactwith: {type: String, index: true}
});
module.exports = mongoose.model('Contact', ContactSchema);
mongoose.model('Contact', ContactSchema).ensureIndexes(function(err) {
if (err)
console.log(err);
else
console.log('create contact index successfully');
});
Controller/contact.js
var mongoose = require('mongoose');
var Contact = mongoose.model('Contact');
var ContactController = function(app,mongoose){
app.post('/search',function(req,res){
var query = req.body.searchbx;
console.log(query);
var dbsearch = Contact.find({$text: {$search: query}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}});
console.log(dbsearch);
Contact.find({$text: {$search: query }}, function (err, results){
if(err){
console.log(err);
}
if(results){
console.log('in results')
console.log(results)
res.render("search",{results: results});
}
})
});
}
module.exports = ContactController;
in jade file
form(id="search-filter" method ="POST" action="/search")
input#search-bx(type='text', name='searchbx' placeholder="search here")
input(type="submit", value="Search")
I hope you are the beginner to nodeJS. Welcome :)
You did lot of things except 2 main things that is important!
Please Read: http://restfulapi.net/http-methods/
You have tried for text search. $text queries to work, mongodb needs to index the field with an text index. You want to do some one changes in your mongoose
{fields: {type: [String], text: true}
REF: https://docs.mongodb.com/v3.2/core/index-text/
Here is the simple and clean code: you can do modification based on the sample
var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', {
name : {type : String, unique: true, text: true},
location: {type: String}
});
Controller:
app.get('/api/todo/search/:searchKey', function (req, res) {
var searchKey = req.params.searchKey;
if (!searchKey) {
return res.send({ reason: 'searchKey required' });
}
Todo.find({
$text: { $search: searchKey }}, function(err, result) {
if (err) {
res.status(500);
return res.send({ reason: err.toString() });
} else if (result && result.reason) {
return res.status(400).send(result);
}
return res.status(200).send(result);
});
});
All the Best!!!