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

Apollo Server报错:Cannot read properties of undefined (reading 'collection')求助

问题分析与解决方案

核心错误原因

报错Cannot read properties of undefined (reading 'collection')的直接原因是:你的ApolloServer实例没有传入配置好的context对象,导致signUp resolver的第三个参数(上下文)中的db为undefined,调用db.collection时触发该错误。

修复步骤

1. 传入context到ApolloServer

修改start函数中创建ApolloServer的代码,将定义好的context对象加入配置:

const server = new ApolloServer({ typeDefs, resolvers, context });

原代码仅传入typeDefs和resolvers,缺少context参数,导致resolver无法获取数据库连接实例。

2. 修复MongoDB废弃API问题

MongoDB的insert方法已被废弃,建议使用insertOne(插入单个文档),同时insertOne返回结果结构与insert不同,需调整用户数据获取逻辑:

// 替换signUp resolver中的数据库插入代码
const result = await db.collection('Users').insertOne(newUser);
// 将插入的ID赋值给newUser,返回完整用户对象
newUser._id = result.insertedId;
return {
  user: newUser,
  token: 'token'
}

3. 其他优化建议(非报错相关,提升代码健壮性)

  • bcrypt.hashSync建议指定盐轮次参数,增强密码哈希安全性:
    const hashedPassword = bcrypt.hashSync(input.password, 10); // 10为推荐的盐轮次
    
  • 修复signIn输入类型的拼写错误,同时修正Mutation定义中的类型引用:
    type Mutation {
        signUp(input: SignUpInput): AuthUser!
        signIn(input: SignInInput): AuthUser! # 改为SignInInput
    }
    
    input SignInInput { # 修正拼写(原先是SingInInput)
        email: String!
        password: String!
    }
    

完整修复后的关键代码片段

start函数部分

const start = async () => {
    const client = new MongoClient(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
    await client.connect();
    const db = client.db(DB_NAME);

    const context = {
        db,
    }

    // 传入context参数
    const server = new ApolloServer({ typeDefs, resolvers, context });

    server.listen().then(({ url }) => {
        console.log(`🚀 server ready at ${url}`);
    });
};

signUp resolver部分

signUp: async (_,{input}, {db}) => {
    const hashedPassword = bcrypt.hashSync(input.password, 10);
    const newUser = {
        ...input,
        password: hashedPassword,
    }
    // 使用insertOne替代insert
    const result = await db.collection('Users').insertOne(newUser);
    newUser._id = result.insertedId;
    return {
        user: newUser,
        token: 'token'
    }
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:54:29