Mongodb + nodejs不与localhost连接

时间:2017-11-06 23:07:58

标签: node.js mongodb express web

我一直在尝试通过nodejs连接本地mongo服务器。 这是官方mongodb给出的简单教程,但没有挂钩once部分。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("connected");
});

这是我项目的package.json:

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "body-parser": "1.4.3",
        "errorhandler": "1.1.1",
        "express": "4.4.4",
        "express-handlebars": "1.1.0",
        "mongoose": "^3.8.8",
        "morgan": "1.1.1"
    }
}

当我输入mongo时,他们会说

MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
Server has startup warnings:
2017-11-07T07:58:20.003+0900 I CONTROL  [initandlisten]
2017-11-07T07:58:20.003+0900 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-07T07:58:20.003+0900 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-07T07:58:20.003+0900 I CONTROL  [initandlisten]

所以它应该在控制台上说connected但不是。 有谁知道如何处理它?我尝试通过brew重新安装mongo。

感谢。

macOS Sierra 10.12.6 节点v7.6.0

3 个答案:

答案 0 :(得分:0)

我认为你必须启动mongodb进程,然后运行mongod Server/3.4/bin/目录。之后尝试连接。

答案 1 :(得分:0)

更新到最新的猫鼬立即解决了问题! 谢谢你的帮助!

答案 2 :(得分:0)

有同样的问题。这是抢救。 在主“ app.js”文件中,使用以下结构:

`mongoose.connect(keys.mongoURI, {useUnifiedTopology: true,useNewUrlParser: 
true,useCreateIndex: true})
.then(() => console.log('MongoDB has been connected!'))
.catch(error => console.log(error));`

然后创建连接文件,在该文件中插入以下代码:     module.exports = { mongoURI: "mongodb+srv://name:password@vlad-m9cz9.mongodb.net/test? retryWrites=true&w=majority" <- here is an example of link, take it from your cluster connection parameter. };

然后转到文件“ app.js”并创建变量并需要连接对象:     const mongoose = require('mongoose'); const keys = require('./config/keys');

然后在mongoDB中插入IP地址以访问数据库

仅此而已!