gpt4 book ai didi

javascript - 错误 : Collection method aggregate is synchronous

转载 作者:行者123 更新时间:2023-12-05 02:37:30 27 4
gpt4 key购买 nike

我正在尝试以下代码:

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

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

我收到以下错误:

[...]\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)

我做错了什么?

最佳答案

好像是mongoose连接数据库的方式有问题。在调用聚合方法之前创建连接但不连接会导致抛出该异常。我应该这样使用它:

// 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() );

令人沮丧的是,异常本身的记录很差。

关于javascript - 错误 : Collection method aggregate is synchronous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69953709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com