Reputation: 363
I am trying to create a script that connects to a MongoDB instance, selects a database, lists all the collections from a database and then creates a schema to use for validation from a sample of documents. The latter half of this I have figured out, but I am completely stumped as to how to do the first part. Here's what I have so far this is file runner.js that I am loading from mongosh by running load("runner.js") in the shell prompt:
async function run() {
const db = connect('mongodb://localhost/mainDB')
// const collections = db.runCommand({
// listCollections: 1.0,
// nameOnly: true
// });
const coll = db.listCollections();
console.log(collections);
for await (const doc of collections) {
console.log(doc);
}
}
run().catch(reason => console.error('ERROR RUNNING: ', reason));
When I run the above, I get the following error: ERROR RUNNING: TypeError: db.listCollections is not a function
Bollocks, the API documentation says it's a method https://mongodb.github.io/node-mongodb-native/6.9/classes/Db.html#listCollections
No matter, though, when I uncomment out the commented section above and use the runCommand method, I get the following error:
{
cursor: {
id: Long('0'),
ns: 'mainDB.$cmd.listCollections',
firstBatch: [
{ name: 'purchaseOrderLineItems', type: 'collection' },
{ name: 'transactionCost', type: 'collection' },
{ name: 'addresses', type: 'collection' },
...<more I am not listing here>
]
},
ok: 1
}
ERROR RUNNING: TypeError: collections is not async iterable
This also doesn't make sense. Documentation here https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/read-operations/cursor/ says that the cursor, (which this is, right) implements the async iterable interface, so this should work.
Would someone clarify what is going on here?
Upvotes: 0
Views: 36