0

I want to search some collection that had a specific field in MongoDB. Say there is two collection that had a name field and the other not.

Using mongoose.js though I found someone asks this, now the answer is outdated. How to do that with nowadays mongoose versions?

Here the code that I tried, I'm successfully getting all the collections name but when I search for the specific fields it doesn't work and gave me no error.

    mongoose.connection.db.listCollections().toArray((error, collections) => {
        collections.forEach( (collection) => {
           var collectionName = mongoose.connection.db.collection(collection.name)
                var count = collectionName.find({ "duck_name": { $exists: true }}).count()
                    if ( count > 0 ){
                        console.log(collection.name)
                        }
                    })
                })

There is no error and no warnings on that code.

Sridhar
  • 11,466
  • 5
  • 39
  • 43
mandaputtra
  • 922
  • 3
  • 18
  • 36
  • Don't mean to derail your question, but I can't think of a practical use case (although one may exist) where you would want to do this. Wouldn't it make more sense to define your schemas ahead of time, and then search for the data you need? – user2263572 Jan 10 '19 at 03:17
  • Yeah there is, in my use case I'm on the already ongoing project, and there is about 20 schema, I know I can search on the schema on the code but maybe I could simplify things by using this approach. – mandaputtra Jan 10 '19 at 03:24
  • What if the same field appears in multiple schemas? What if someone a month from now adds a new schema with this field?....this approach will not simplify anything. If you are using this code as a programming tool, just about every IDE available has search capability that will work faster than this. – user2263572 Jan 10 '19 at 03:28
  • That's why I need to do this. It will simplify many things, see if there is 10 schema and you want to update all "duck name" on the collection you can just use `forEach() ` and all "duck_name" value on the collections all changed – mandaputtra Jan 10 '19 at 03:45
  • "I don't know what fields are in what schemas, I don't want to spend the time to understand where/how I'm storing data, but I want to programmatically update all my schemas". Godspeed. – user2263572 Jan 10 '19 at 03:50
  • "Don't mean to derail your question" ? please be **const** if you can answer the question answer it. don't say to me the good and bad practice on the code, or how to do it. Its just question and there is an answer. I may use the solution given by the other person, I may not. It's up-to-me. Thanks. – mandaputtra Jan 10 '19 at 14:35

1 Answers1

0

mongoose.connection returns native mongodb connection which everything that You do using db. prefix is same as You do directly on mongodb console.

So don't wait from mongoose act the same when You're using native connection descriptor.

When You work with collections natively You've to understand that find method returns cursor.

const db = mongoose.connection.db;
const collections = db.listCollections()

collections
  .toArray((error, collections) => {
    collections.foreach(async collection => {
      const query = {"duck_name": { $exists: true }};
      const count = await collection.find(query).count();
      if (count === 0) return;

      console.log('Found:', count, 'documents in collection:', collection.name);
      const cursor = await collection.find(query);
      while(await cursor.hasNext()) {
        const document = await cursor.next();
        console.log('document:', document._id);
      }
    })
  });   

or use toArray method on cursor:

const db = mongoose.connection.db;
const collections = db.listCollections()

collections
  .toArray((error, collections) => {
    collections.foreach(async collection => {
      const query = {"duck_name": { $exists: true }};
      const count = await collection.find(query).count();
      if (count === 0) return;

      console.log('Found:', count, 'documents in collection:', collection.name);
      const documents = await collection.find(query).toArray();
      for(const document of documents) {
        console.log('document:', document._id);
      }
    })
  });  
num8er
  • 18,604
  • 3
  • 43
  • 57