I am writing a very simple application with NodeJS and Mongoose.
If I disable authentication in Mongoose, everything works fine and I can access my records from the database. But when I turn on the authentication and configure my NodeJS code to use authenticated Mongoose connection it doesn't let me query my records and the web page keeps on loading.
Name of my database is "bears".
P.S. I have created my users in "Admin database and Bears" database. I have given a user of books database readwrite permissions and it works fine when I authenticate it through "Mongo" command or db.auth command. But it is not working through NodeJS/Mongoose.
Here is my code.
var mongoose = require('mongoose');
var opt = {
user: 'bearsdev',
pass: 'bearsdev123!',
auth: {
authdb: 'bears'
}
};
mongoose.connect('mongodb://localhost:27017/bearsdev',opt);
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
In my server.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var Bear = require('../models/bear');
var bear = require('express').Router();
bear.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
bear.get('/bear',function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
app.use('/test', bear);
app.listen(8080);
localhost:8080/test works. localhost:8080/test/bear keeps on loading.
I have tried different ways of authentication with Mongoose, e.g.
mongoose.connect('mongodb://bearsdev:bearsdev123!@localhost:27017?authSource=bearsdev');
and
mongoose.connect('mongodb://bearsdev:bearsdev123!@localhost:27017/bearsdev');
None of these ways are working for me.
答案 0 :(得分:3)
我希望以下代码可以正常工作。
database = {
host: 'localhost',
db: 'bears',
port: '27017',
options: {
user: "bearsdev",
pass: "bearsdev123!",
auth: {
authdb: 'admin'
}
}
}
mongoose.connect(database.host, database.db, database.port, database.options, function (err) {
if (err) {
console.log("connection error:", err);
} else {
console.log("MongoDB connection successful");
}
});
答案 1 :(得分:0)
我能够通过卸载Mongoose的本地节点模块然后安装最新版本来解决问题。可能有些中间版本(~3.6.13)有这个bug。但最新的Mongoose很不错。