为什么Node.js上会出现"TypeError:client.db不是函数",我该如何修复



我正在nodejs中编写mongodb聚合查询。我尽力想弄清楚,但代码在我的方法中不起作用。我得到以下错误:TypeError:client.db不是函数

const { MongoClient, ObjectId } = require('mongodb');

async function main(){

const uri = `mongodb://${dbUser}:${dbPassword}@${ipAddress}:${port}/${dbName}`;

const client = new MongoClient(uri);

try {

await client.connect();

await printStudents("541516516165164489d3aee");

} finally {
await client.close();
}
}

main().catch(console.error);

/**
* Print the students for a given schoolId
* @param {MongoClient} client A MongoClient that is connected to a cluster with the education database
* @param {ObjectId} schoolId
*/

async function printStudents(client,schoolId){
const pipeline = [
{ 
'$match' : { '_id' : ObjectId(schoolId) } 
},
{
'$project': 
{
'_id':  { '$toString': '$_id'}
}
},
{
'$lookup':
{
'from': 'students',
'localField': '_id',
'foreignField': 'schools',
'as': 'Students'
}
}
]; 

const aggCursor = client.db("education").collection("schools").aggregate(pipeline);

await aggCursor.forEach( err => {
console.log(`${err._id}: ${err.$lookup}`);
});
}

我希望我能得到一些关于如何正确解决这个问题的好建议

您将传递一个字符串作为第一个参数,它应该是mongodb客户端。

更改自:

await printStudents("541516516165164489d3aee");

至:

await printStudents(client,"541516516165164489d3aee");

在调用printStudents方法时,您没有将客户端对象作为参数传递。通过调用printStudents("541516516165164489d3aee"),客户端参数是一个字符串,schoolId参数是未定义的。您应该改为呼叫printStudents(client, "541516516165164489d3aee")

最新更新