if someone needs it
index.js
var express = require('express'),
autocomplete=require('./routes/autocomplete');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/autocomplete/:search',autocomplete.find);
app.listen(6000);
console.log('Listening on port 3000...');
autocomplete.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('redsocial', server);
db.open(function(err, db) {
if (!err) {
console.log("Connected to 'mydb' database");
db.collection('publication', {strict: true}, function(err, collection) {
if (err) {
console.log("error");
}
});
}
});
exports.find = function(req, res) {
var b=req.params.search;
db.collection('publication', function(err, collection) {
collection.find({type:'pub',content: new RegExp(b,'i')}).limit(5).toArray(function(err, items) {
res.jsonp(items);
});
});
};
jquery
$('#search').autocomplete({
source: function(req,res) {
$.ajax({
url: "http://www.ejemplo.com:3000/autocomplete/"+req.term,
dataType: "jsonp",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.text,//text comes from a collection of mongo
value: item.text
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
select: function(event, ui) {
}
});
Source Code: Link
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…