错误:无法读取null的属性"close" [英] Error: Cannot read property 'close' of null

查看:298
本文介绍了错误:无法读取null的属性"close"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好亲爱的社区,我想知道为什么我在尝试使用mongodb和nodejs时出现此错误.

hello dear community im wondering myself why i get this error when i try to use mongodb and 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();
});

控制台中的输出:

无法连接到MongoDB服务器. C:\ Users \ eljubec \ Desktop \ node-todo-api \ node_modules \ mongodb \ lib \ mongo_client.js:421 抛出错误 ^

Unable to connect to MongoDB server. C:\Users\eljubec\Desktop\node-todo-api\node_modules\mongodb\lib\mongo_client.js:421 throw err ^

TypeError:无法读取null的属性"close" 在MongoClient.connect(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 在process._tickCallback(internal/process/next_tick.js:150:11)

TypeError: Cannot read property 'close' of null at MongoClient.connect (C:\Users\eljubec\Desktop\node-todo-api\playground\mongodb-connect.js:9:8) at connectCallback (C:\Users\eljubec\Desktop\node-todo-api\node_modules\mongodb\lib\mongo_client.js:527:5) at 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)

推荐答案

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

You might want to check if your MongoDB service is up and running on the given port. Open a Command Prompt (WindowsKey+R->cmd->OK) and run the following command:

netstat -a | find "27017"

这应该给你这样的输出:

This should give you some output like this:

TCP    127.0.0.1:27017        <MACHINE_NAME>:0         LISTENING

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

If you don't see this line you need to start MongoDB or make sure it runs on the default port.

第二个错误"Cannot read property 'close' of null"仅仅是因为连接失败,所以您的db变量将根据

The second error "Cannot read property 'close' of null" is simply because the connection fails so your db variable will hold a null value according to the docs which obviously you cannot run a close() on. You might want to move that close() statement inside the else statement.

这篇关于错误:无法读取null的属性"close"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆