我有一个小型的Node.js / Express / Mongoose应用程序我在使用Bitnami AMI构建的AWS-EC2实例上运行,每当我尝试使用Chrome Postman在我的应用程序MongoDB集合上运行.find我得到以下结果
{
"name": "MongoError"
}
[MongoError: not authorized for query on projectDB.areas]
我尝试使用以下3个连接字符串,但所有3个返回了相同的结果,有人可以通过告诉我在这里错过/做错了吗?感谢
var connectionString = 'mongodb://localhost:27017/'+dbName;
var connectionString = 'mongodb://root:bitnami@localhost:27017/'+dbName;
var connectionString = 'mongodb://root@localhost:27017/'+dbName;
我的node.js应用代码:
area.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var areaSchema = new Schema({
name: { type: String, required: true },
});
module.exports = mongoose.model('Area', areaSchema);
areas.js
var Area = require('../app/models/area');
var express = require('express');
var router = express.Router();
router.route('/').get(function(req, res){
Area.find(function(err, areas){
if(err){
return res.send(err);
}
res.json(areas);
//res.send({sucess:true, areas:areas})
});
});
app.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var areas = require('./routes/areas');
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(bodyParser.json({ type: 'application/*+json' }));
var dbName = 'projectDB';
var connectionString = 'mongodb://localhost:27017/'+dbName;
// var connectionString = 'mongodb://root:bitnami@localhost:27017/'+dbName;
// var connectionString = 'mongodb://root@localhost:27017/'+dbName;
////////Tried the above 3 connection strings, none worked...
mongoose.connect(connectionString, function(err){
if(err){
throw err;
}
});
var corsOptions = {
origin: '*',
allowedHeaders: ['Content-Type'],
methods: ['POST','GET','PUT','DELETE'],
credentials: true
};
app.use(cors(corsOptions));
app.use('/api/areas', areas);
module.exports = app;
www.js
var app = require('../app');
var server = app.listen(app.get('port'), function(){
console.log('Server running on port: '+ server.address().port);
});
答案 0 :(得分:0)
因为,运行$ mongo admin --username root --password bitnami
并没有带你进入Mongo shell。
假设您在服务器而不是本地计算机上运行该代码,这仅表示您的MongoDB未正确设置。您应该完全从AWS中删除该实例并从头开始设置。否则,只需按照MongoDB网站上的说明安装MongoDB。
此外,对于Node.js,请使用以下代码确保您已实际连接:
`
mongoose.connect("mongodb://root@localhost:27017/projectDB");
var db = mongoose.connection;
db.once('open', function () {
console.log('MongoDB connection successful.');
});
`