首页 文章

错误:无法读取属性'close'的null

提问于
浏览
0

你好亲爱的社区我想知道为什么当我尝试使用mongodb和nodejs时我得到这个错误 .

const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
    if (err) {
        console.log('Unable to connect to MongoDB server.')
    }else{
        console.log('Connected to MongoDB server.')
    }
    db.close();
});

输出 console

无法连接到MongoDB服务器 . C:\ Users \ eljubec \ Desktop \ node-todo-api \ node_modules \ mongodb \ lib \ mongo_client.js:421 throw err ^ TypeError:无法在MongoClient.connect中读取null的属性'close'(C:\ Users \ eljubec \ desktop \ node-todo-api \ playground \ mongodb-connect.js:9:8)在connectCallback(C:\ Users \ eljubec \ Desktop \ node-todo-api \ node_modules \ mongodb \ lib \ mongo_client.js:527) :5)在C:\ Users \ eljubec \ Desktop \ node-todo-api \ node_modules \ mongodb \ lib \ mongo_client.js:418:11 at process._tickCallback(internal / process / next_tick.js:150:11)

1 回答

  • 2

    您可能想要检查MongoDB服务是否已在给定端口上启动并运行 . 打开命令提示符( WindowsKey+R->cmd->OK )并运行以下命令:

    netstat -a | find "27017"
    

    这应该给你一些像这样的输出:

    TCP    127.0.0.1:27017        <MACHINE_NAME>:0         LISTENING
    

    如果您没有看到此行,则需要启动MongoDB或确保它在默认端口上运行 .

    第二个错误 "Cannot read property 'close' of null" 只是因为连接失败所以 db 变量将根据docs保持 null 值,显然你无法运行 close() . 您可能希望在 else 语句中移动该 close() 语句 .

相关问题