I am trying to get records using a rest service implemented with node js to populate a autocomplete of jquery. Here is the method
db.collection('publication', function(err, collection) {
collection.distinct('title',{'$or':[{type:'an'},{type:'pub'}]}).toArray(function(err, items) {
res.jsonp(items);
});
});
};
The query in mongo works ->
db.publication.distinct('title',{'$or':[{type:'an'},{type:'pub'}]})
returns [ "Product", "Event" ] but the result is different when I use find, with find would be->
{ "_id" : ObjectId("51fbb2124e49d03810000000"), "title" : "Anuncio" }
{ "_id" : ObjectId("51fbb2ae4e49d03810000001"), "title" : "Evento" }
With the second way the autocomplete works, but with the first not
The error shown in node is: object is not a function.
Finally what I need is to return a json with the records to populate the autocomplete which is populated like this:
$('#search').autocomplete({
source: function(req, res) {
$.ajax({
url: "http://www.example.com:3000/autocomplete/" + req.term ,
dataType: "jsonp",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.title,
value: item.title
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
});
try to move the function part into the distinct().
collection.distinct('title',{'$or':[{type:'an'},{type:'pub'}]},function(err, items) {
res.jsonp(items);
});
I ran into the same problem and I fixed my problem here:
http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
(search for the key word 'distinct')
It turns out that the official doc do help
Hope it helps whoever have the same problem.
Should exclude the _id field in your search
Query:
db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1, _id: 0 } )