Home > Software design >  Error: Collection method aggregate is synchronous
Error: Collection method aggregate is synchronous

Time:11-16

I'm trying the following code:

const Conn = mongoose.createConnection('mongodb://127.0.0.1:27017/db');

const addresses = Conn.collection('users').aggregate([
  {
    $project: {
      _id: false,
      ethAddr: true,
    }
  }
]);

I receive the following error:

[...]\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:100
        throw new Error('Collection method '   i   ' is synchronous');
              ^

Error: Collection method aggregate is synchronous
    at NativeCollection.<computed> [as aggregate] ([...]\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:100:15)
    at file:///[...]/backend/scripts/dbGetMerkleRoot.js:11:46
    at file:///[...]/backend/scripts/dbGetMerkleRoot.js:28:3
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

What in cattle's name I'm doing wrong?

CodePudding user response:

It seems to be a problem with the way mongoose connects to the database. Creating the connection but not connecting prior to invoking the aggregation method causes that exception to be thrown. I should've used it this way:

// create custom connection
const Conn = mongoose.createConnection();

// connect to database
await Conn.openUri('mongodb://127.0.0.1:27017/db');

// @type {AggregationCursor}
const addresses = Conn.collection('users').aggregate([
  {
    $project: {
      _id: false,
      ethAddr: true,
    }
  }
]);

console.log( await addresses.toArray() );

It's frustrating the exception itself is poorly documented.

  • Related