You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js出现TypeError: client.db is not a function报错的原因及修复方法

MongoDB聚合查询报错修复方案

错误根因

你触发TypeError: client.db is not a function的核心问题是传参不匹配:

  • 你定义的printStudents函数要求第一个入参是已连接的MongoClient实例,第二个入参是schoolId
  • 但你在main函数中调用printStudents时,只传了schoolId字符串,导致printStudents内部拿到的client变量实际是字符串,字符串本身没有db方法,直接抛出类型错误

除此之外你还有两处影响执行的小问题:

  1. 聚合查询的返回结果中,关联查询的结果保存在你定义的as字段Students中,不是$lookup字段
  2. aggCursor.forEach的回调参数是查询到的文档对象,不是错误对象,原命名err会导致语义混淆

修复后可运行代码

const { MongoClient, ObjectId } = require('mongodb');
// 此处请自行补全dbUser、dbPassword、ipAddress、port、dbName变量定义
async function main(){
    const uri = `mongodb://${dbUser}:${dbPassword}@${ipAddress}:${port}/${dbName}`;
    const client = new MongoClient(uri);
    try {
        await client.connect();
        // 修复点1:传入MongoClient实例作为第一个参数
        await printStudents(client, "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 {string} 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);
    // 修复点2:修改回调参数命名和打印字段
    await aggCursor.forEach(doc => {
        console.log(`${doc._id}: ${doc.Students}`);
    });
}

内容的提问来源于stack exchange,提问作者Sansli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 16:06:03