[英]cannot connect to mongo local DB from Node JS
我正在学习 Mongo DB、Mongoose 和 Node JS,但似乎无法将 Node JS 连接到本地 Mongo DB。
这是我的代码:
dbtest.js
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
var Todo = mongoose.model('Todo', {
text : String
}, 'test');
var status = {
"status": "not connected"
};
app.get('/api/todos', function(req, res) {
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
{
if (err) {
res.json(status);
} else {
res.json('Connected');
}
});
});
app.listen(8080);
console.log("App listening on port 8080");
当我调用 api/todos GET 请求时,返回了状态 JSON 对象,这意味着我无法连接到数据库。
我完全安装了 MongoDB Enterprise Server 3.14.10 并运行了它,但我不知道为什么我的 NodeJS 应用程序无法连接。
任何建议表示赞赏。
您的第一个mongoose.connect()
参数缺少用户名/密码组合:
mongoose.connect('mongodb://username:password@127.0.0.1:27017/exampleDB');
尝试在执行任何操作之前先连接数据库。 连接后尝试在您的自定义函数中使用。 下面的代码将帮助您测试本地数据库
const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
console.log('Connected to database ');
});
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
检查您的 cmd 窗口以查看控制台。
要连接到本地 mongodb,您可以使用此 URI,将 USER, PASSWORD are DB 替换为您的值:
mongodb://USER:PASSWORD@127.0.0.1/DB?authSource=admin
您不需要提供端口 27017,因为它是 mongodb 的默认端口。
这里的技巧是添加 'authSource=admin' 以启用身份验证。
文档: https : //docs.mongodb.com/manual/reference/connection-string/#examples
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.