[英]Mongoose nodejs - authentication failed trying to connect to mongodb docker
I'm trying to connect to a mongodb container using mongoose. This is my docker-compose
:我正在尝试使用 mongoose 连接到 mongodb 容器。这是我的
docker-compose
:
version: "3"
networks:
mongonet:
services:
mongodatabase:
image: mongo
container_name: mongodatabase
ports:
- 27017:27017
environment:
- MONGO_INITDB_DATABASE=admin
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
networks:
- mongonet
mongojs:
depends_on:
mongodatabase:
condition: service_started
container_name: mongojs
build: .
ports:
- 8080:8080
environment:
- MONGO_URI=mongodb://mongodatabase:27017/test
networks:
- mongonet
Containers start and work ok, but problems appear when using mongoose:容器启动正常,但使用mongoose时出现问题:
const mongoose = requrie('mongoose')
const {MONGO_URI} = require('./../config/env')
exports.__mongo_ini = async function () {
const connectOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try {
await mongoose.connect(MONGO_URI, connectOptions)
console.info(`===> Connected to database ${MONGO_URI}`)
}
catch(err) {
console.warn(`===> Couldn't connect: ${err}`)
}
}
When using the env URI mongodb://mongodatabase:27017/test
It says connected.当使用 env URI
mongodb://mongodatabase:27017/test
它表示已连接。 But then If I try to find a model:但是如果我试图找到一个 model:
await models.Star.find().catch(r => r)
I get the error:我收到错误:
MongoServerError: command find requires authentication
at Connection.onMessage (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:203:30)
at MessageStream.<anonymous> (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:63:60)
....
ok: 0,
code: 13,
codeName: 'Unauthorized',
[Symbol(errorLabels)]: Set(0) {}
}
My model:我的model:
const starSchema = new mongoose.Schema({
starName: {
type: String,
unique: true,
required: true
},
image: {
type: String
},
designation: {
type: String
},
constelation: {
type: String
},
named: {
type: Date
},
timeStamp: {
type: Date,
default: Date.now()
}
})
const Star = mongoose.model('Star',starSchema)
module.exports = Star
Tried to add a mongo entrypoint volume in my docker compose:试图在我的 docker 撰写中添加一个 mongo 入口点卷:
volumes:
- ./mongo-entrypoint/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
Mongo-init.js: Mongo-init.js:
db.getSiblingDB('admin').createUser({
user: 'testuser',
pwd: 'testpass',
roles: [
{
role: 'readWrite',
db: 'test'
}
]
})
db.getSiblingDB('test').createCollection('collection_test');
So I try to connect changing the mongo uri to use user and password:所以我尝试连接更改 mongo uri 以使用用户和密码:
MONGO_URI=mongodb://testuser:testpass@mongodatabase:27017/test
But It says authentication failed when trying to connect to the mongo uri and the mongo entrypoint doesn't seem to run:但它说在尝试连接到 mongo uri 时身份验证失败并且 mongo 入口点似乎没有运行:
Couldn't connect: MongoServerError: Authentication failed.
I've tried so many things and none of them work.我尝试了很多东西,但没有一个起作用。 All help is appreciated.
感谢所有帮助。
Try this code in node.js在 node.js 中尝试此代码
database.js数据库.js
require("dotenv").config();
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connection SUCCESS");
} catch (error) {
console.error("MongoDB connection FAIL");
}
};
module.exports = connectDB;
.env .env
MONGO_URI=your_mongodb_url
Create a models file models.js创建模型文件 models.js
const mongoose = require("mongoose");
const CategorysSchema = new mongoose.Schema({
description: {
type: String,
lowercase: true,
},
name: {
type: String,
lowercase: true,
},
publishedAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("categorys_collection", CategorysSchema);
Find Models查找模型
const Category_Model = require("./models");
app.get("/", async (req, res) => {
try {
const Category = await Category_Model.find();
res.json(Category);
} catch (error) {
res.status(500).json({ message: error.message, status: "error" });
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.