我正在学习如何在 Amazon 的 Cloud 9 上编写代码,并且正在尝试从 NodeJS 连接到 MongoDB 数据库,但是当我调用该connect()
函数时db
,回调中返回的函数是未定义的。但是,当我在 mongo shell 中运行时,我可以看到数据存在show dbs
,并且 mongo 服务器运行没有问题,并且connect()
函数本身不会抛出任何错误。
index.js:这是包含 MongDB 连接的index.jsnpm start
文件(当我在终端中运行时执行此文件):
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/testdb", function (err, db) {
if (err){ console.log(err)}
else{
console.log("Connected!")
console.log(db.name)
}
db.close()
})
mongo shell确认数据库存在(sample
是集合的名称):
use testdb
switched to db testdb
db.sample.find()
{ "_id" : ObjectId("5aed5fc7a44ab7d8a4efce2f"), "name" : "Luckyfield" }
mongo 服务器正在运行,因为它说“等待端口 27017 上的连接”,每当我运行 index.js 文件时,该服务器都会记录终端中的连接打开和关闭:
connection accepted from 127.0.0.1:43820 #16 (1 connection now open)
2018-05-05T11:07:16.128+0000 I NETWORK [conn16] received client metadata from 127.0.0.1:43820 conn16: { driver: { name: "nodejs", version: "3.0.7" }, os: { type: "Linux", name: "linux", architecture: "x64", version: "4.9.91-40.57.amzn1.x86_64" }, platform: "Node.js v6.14.1, LE, mongodb-core: 3.0.7" }
2018-05-05T11:07:16.138+0000 I NETWORK [conn16] end connection 127.0.0.1:43820 (0 connections now open)
当我替换db.name
为 justdb
时,控制台会显示一个充满数据的 MongoClient 对象,尽管我不知道它是什么。我也尝试插入或查询文档,但同样,db 似乎未定义。
总之,当我npm start
在单独的终端中运行时,index.js文件会在控制台中执行并打印undefined
,即使连接已正确建立并且数据实际存在。感谢您的任何帮助!