0

I have some problem in crating an autocomplete search box. I have a mongodb collection in which there are photos object with name, description, path and so on. Now, I created a route /searchbox, where the box is displayed in the browser. Every time that the user press a key, a get request to the route /autocomplete/:query is made. The autocomplete route will search in the collection for all the objects where the name, the description or the keywords fields starts with the give query. Then it return a json object containing all the strings that will be put into a datalist in the view. The problem is that I can't create that json array, I tried to create a json object with a field containing an array, and at every iteration on the found array returned by the find function, I get the field name and push it into the array, but nothing is added... here my code:

exports.autoComplete = function(req, res) {
  var PhotoAlbum = db.model('PhotoAlbum', schemas.PhotoAlbumSchema);
  var regexp = "^"+req.params.query;
  var suggestions = {suggestion: []};

  var strings = "";
  var arrayStrings = [];


  PhotoAlbum.find({name: new RegExp(regexp,"i")}, function(err, found) {
    if(err) throw handleError(err);
    for(obj in found) {
      var name = found[obj].name;
      suggestions.suggestion.push(name);
      strings += name + "|";
    }


  });
}

Thank you

11
  • And you did console log found to see that it actually contains something ? Commented Nov 17, 2013 at 21:37
  • Yes, it contains the right objects Commented Nov 17, 2013 at 21:38
  • And that's not all your code, right? You have a res.send( JSON.stringify(suggestion) ) somewhere ? Commented Nov 17, 2013 at 21:38
  • Yes yes sure I forgot to add it Commented Nov 17, 2013 at 21:39
  • I also tried to create an array by splitting a string created by concatenating all the name fileds (not so elegant), but anyway in the view I get an empty array Commented Nov 17, 2013 at 21:40

1 Answer 1

1

That looks like Mongoosejs with MongoDB.

IF it is, in that case, its not returning an object at "found". "found" is a collection that is an array already in which you would iterate through it like so:

for(var i = 0; i < found.length; i++) {
   console.log(found[i]);
   // your code
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes its mongoose. I tried also with the normal for, but nothing works
I can iterate on it, but when I try to add a new string with push(), nothing is added

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.