1

I'm trying to search in all collections in one database but I have no idea howto return data at the end of the forEach cycle. I understand this is a place for Promise or async/await but don't know how to properly use it after forEach :-(

//db.js    
var MongoClient = require('mongodb').MongoClient;

    module.exports = {
      searchAllCollections: function() {
        return MongoClient.connect('mongodb://localhost:27017/nodeLists', {poolSize: 10}).then(function(db) {
          var ipList = [];
          db.listCollections().forEach((doc) => {
            console.log(doc.name);
            db.collection(doc.name).find({ip: "192.168.0.1"}).toArray((err, data) => {
              console.log(data);
              ipList.push(data);
            });
          });
        });
      }
    };


//app.js
var db = require('./db');

db.searchAllCollections().then(function(items) {
  console.info('Returned data:',items);
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});
Marian
  • 33
  • 4
  • Before your question gets hammered with the obvious duplicate, why are you searching in multiple collections in the first place? If somehow you've arrived at this as a requirement, then your design is wrong. If you need to do this sort of thing then you should have put the data in a single collection. Why is it in several? – Neil Lunn Aug 31 '17 at 10:01
  • I'm new in Javascript & Mongo and maybe that's reason why my schema design is not correct. Trying to build own inventory of nodes, their processes, network devices etc. That's why I have Collection of nodes, processes and some else. Now I need to search across them. Maybe it ids not good ide but it is remnant of my old habits. I'm going to look at links what you mentioned above. – Marian Aug 31 '17 at 11:05
  • The problem was I didn't understand Promises and async/await enough.Thanks to https://www.youtube.com/watch?v=BQnGPzTKBS4&t=1513s I was able to adjust function as I needed. Nevertheles I will revise my mongodb schema. – Marian Sep 01 '17 at 13:02

0 Answers0