This is pretty ugly now. My main objective is to perform a search query, which I do via mongoosastic / elastic search (the search paginates 12 items at time). Then, I want to match those results with a separate "Following" collection.

I find documents from the "Following" collection by the current user's Id, then I use the for loop to match those documents with the returned array of objects provided by the search query -- to mark them as already followed if they match.

I'm looking for a more elegant node solution, but my main concern is: what is the most scalable / performant way to do this?

If the Following collection greatly increases in size (as there is no limit to how many follows a user can have), would that result in atrocious response times for the current function?

exports.topSearch = function(req, res) {
          query_string: {
            query: req.body.search
        }, {
          from: req.body.fromNum,
          size: req.body.size,
          hydrate: req.body.hydrate
        function(err, results) {
          if (err) console.log('ERR', err);
          if (results) {
            var data = results.hits.hits;        

              userId: req.user._id
            }, function(err, docs) {
              if (!err) {
                for (var i = 0; i < docs.length; i++) {
                  for (var j = 0; j < data.length; j++) {
                    if (data[j]._id == docs[i]['productId']) {
                      data[j]['followed'] = true;
                    console.log('data', data[j]);

          } else {
              errmsg: 'results not defined'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.