mongoose没有连接到localhost
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongoose没有连接到localhost相关的知识,希望对你有一定的参考价值。
在尝试创建mongoose连接时,我似乎遇到了问题。我正在关注2014年出版的一本书,所以我的立即回应是检查mongoose文档,但他们同意本书提供正确的格式。以下是我的联系:
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
一旦我添加这些行,我收到以下错误:
Mongoose connection error: mongodb://127.0.0.1/Loc8r
(node:743) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
如果我删除连接,我没有错误......但这会破坏尝试连接到数据库的目的。我也尝试在localhost
的URI中替换127.0.0.1
,这已知可以解决一些问题,但我也没有运气。我通过终端在一个简单的localhost
命令上运行$nodemon
而没有别的。
有用信息:
- MongoDB v3.6.3
- 猫鼬v5.0.10
- 快递vp.15.5
- 所以v8.9.4
帮助将不胜感激。
谢谢。
试试这种方式
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
你正走在正确的道路上,但你忘了把MongoDB运行的端口,MongoDB在端口27017
上运行
不要忘记启动MongoDB服务器,如果你在mac
打开终端并输入mongod
它将启动你的MongoDB服务器然后运行你的代码它将工作正常。
var dbURI = 'mongodb://localhost:27017/Loc8r';
mongoose.connect(dbURI);
mongoose.connection.on("connected", () => {
console.log("Connected to database");
});
mongoose.connection.on("error", (err) => {
console.log("Database error:" + err);
});
我为此道歉,因为我能够自己找到解决方案,但我想有一天这可能对其他人有所帮助。
故障在于我只通过Homebrew安装MongoDB,并且一旦MongoDB被“安装”并且认为MongoDB被“安装”,我就停止了。我回过头来看看MongoDB应该如何正确安装,我注意到我没有创建目录/data/db
并给它权限,这是一个重要的步骤。
一旦我这样做,我在全球运行mongod
,并在一个单独的终端上运行nodemon
,本地在应用程序的根目录,它完全正常,并在控制台中获得了成功的消息。每当我尝试连接时,它都在搜索/data/db
,它显然找不到,因为我没有找到它。但如果Nikhil没有提到运行mongod
,我就不会得出这个结论。
总而言之,请确保您将来遵循所有安装步骤。
以上是关于mongoose没有连接到localhost的主要内容,如果未能解决你的问题,请参考以下文章