我正在 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}`);
});
}
我希望我能得到一些关于如何正确解决问题的好建议。 :)
答案 0 :(得分:0)
您正在传递一个字符串作为第一个参数,它应该是 mongo db 客户端。
更改自:
await printStudents("541516516165164489d3aee");
到:
await printStudents(client,"541516516165164489d3aee");
答案 1 :(得分:0)
在调用 printStudents
方法时,您没有将客户端对象作为参数传递。通过调用 printStudents("541516516165164489d3aee")
,客户端参数是一个字符串,而 schoolId 参数是未定义的。
您应该改为调用 printStudents(client, "541516516165164489d3aee")
。