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

报错TypeError: Cannot read property 'collection' of null,求代码解决方案

解决"Cannot read property 'collection' of null"错误

问题原因

调用addProduct时数据库连接未完成,导致db.get()返回null,无法调用collection方法;同时代码存在几处拼写错误需要修正。

解决步骤

  1. 确保先完成数据库连接再执行操作
    在项目入口文件(如app.js)中,先调用connect方法并等待连接成功,再启动服务或执行数据库操作:
const db = require('./config/connection'); // 根据你的文件路径调整

db.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    process.exit(1);
  }
  console.log('数据库连接成功');
  // 在这里启动服务器或执行其他依赖数据库的逻辑
  const express = require('express');
  const app = express();
  // ... 其他业务代码
  app.listen(3000, () => console.log('服务器运行在3000端口'));
});
  1. 修正代码中的拼写错误
  • 将conection.js文件名改为connection.js(避免路径引用错误)
  • helpers.js里的data.insertdld改为data.insertedId
  • 为addProduct增加无连接时的错误判断,避免程序崩溃

修正后的完整代码

connection.js

//--connection.js--//

const mongoClient = require('mongodb').MongoClient;
const state = {
    db: null
};

module.exports.connect = function(done) {
    const url = 'mongodb://localhost:27017';
    const dbname = 'shopping';

    mongoClient.connect(url, (err, client) => {
        if (err) return done(err);
        state.db = client.db(dbname);
        done();
    });
};

module.exports.get = function() {
    return state.db;
};

helpers.js

//--helpers.js--//

const db = require('../config/connection');

module.exports = {
    addProduct: (product, callback) => {
        console.log(product);
        
        const database = db.get();
        if (!database) {
            return callback(new Error('数据库尚未连接'));
        }
        
        database.collection('product').insertOne(product)
            .then((data) => {
                console.log(data);
                callback(null, data.insertedId);
            })
            .catch((err) => {
                callback(err);
            });
    }
};

进阶优化(使用async/await)

若想简化代码逻辑,可将连接方法改为异步函数:

// connection.js 异步版本
const mongoClient = require('mongodb').MongoClient;
const state = {
    db: null
};

module.exports.connect = async function() {
    const url = 'mongodb://localhost:27017';
    const dbname = 'shopping';
    try {
        const client = await mongoClient.connect(url);
        state.db = client.db(dbname);
        console.log('数据库连接成功');
    } catch (err) {
        throw err;
    }
};

module.exports.get = function() {
    return state.db;
};

入口文件中使用await启动:

const db = require('./config/connection');

async function startApp() {
    try {
        await db.connect();
        // 启动服务器等操作
    } catch (err) {
        console.error('启动失败:', err);
        process.exit(1);
    }
}

startApp();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:15:37