简体   繁体   English

无法使用 mongoose 连接到 mongodb 数据库

[英]Cant connect to mongodb database using mongoose

Hey so i have a school assignment that requires me to connect to a mongodb database with mongoose and koa.嘿,所以我有一个学校作业,需要我使用 mongoose 和 koa 连接到 mongodb 数据库。 I have my database set up on Docker and i can access it through mongodb Compass so that should be all right.我在 Docker 上设置了我的数据库,我可以通过 mongodb Compass 访问它,所以应该没问题。 But when i try to use mongoose, i get an error message on the docker display.但是当我尝试使用 mongoose 时,我在 docker 显示器上收到一条错误消息。

My code:我的代码:

server.js服务器.js

const Koa = require('koa');
const mongoose = require('mongoose');

const router = require('./routes');


const app = new Koa();
app.use(require('koa-body')());
app.use(router.routes());

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        const listener = app.listen(process.env.APP_PORT || 3000, () =>
            console.log('App started on port ' + listener.address().port)
        )
    })
    .catch((error) => {
        console.log(error)
        process.exit(1)
    })

//    app.proxy = true;
module.exports = app;

docker-compose.yml docker-compose.yml

mongodb:
    image: 'mongo:4.4.0'
    command: '--auth'
    container_name: mongodb_container
    volumes:
      - './data/mongo:/data/db:delegated'
    ports:
      - '27017:27017'
    environment: 
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
      MONGO_INITDB_DATABASE: database1

  node-service-two:
    depends_on:
      - mongodb
    build:
      context: '../Test-II-node'
    ports:
      - '3000:3000'
    volumes:
      - '../Test-I-node:/home/node/app:delegated'
    environment:
      MONGODB_URI: mongodb://root:example@localhost:27017/two?authSource=admin
    command: 'run dev'

scripts from package.json来自 package.json 的脚本


  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/server.js",
    "dev": "nodemon src/server.js"
  }

the error message错误信息

[nodemon] starting `node src/server.js`

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

at NativeConnection.Connection.openUri (/home/node/app/node_modules/mongoose/lib/connection.js:800:32)

at /home/node/app/node_modules/mongoose/lib/index.js:341:10

at /home/node/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5

at new Promise (<anonymous>)

at promiseOrCallback (/home/node/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)

at Mongoose.connect (/home/node/app/node_modules/mongoose/lib/index.js:340:10)

at Object.<anonymous> (/home/node/app/src/server.js:11:10)

at Module._compile (internal/modules/cjs/loader.js:1075:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:1096:10)

at Module.load (internal/modules/cjs/loader.js:940:32)

at Function.Module._load (internal/modules/cjs/loader.js:781:14)

at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)

at internal/main/run_main_module.js:17:47 {

reason: TopologyDescription {

type: 'Single',

setName: null,

maxSetVersion: null,

maxElectionId: null,

servers: Map(1) { 'localhost:27017' => [ServerDescription] },

stale: false,

compatible: true,

compatibilityError: null,

logicalSessionTimeoutMinutes: null,

heartbeatFrequencyMS: 10000,

localThresholdMS: 15,

commonWireVersion: null

}
}

[nodemon] app crashed - waiting for file changes before starting...

Im pretty sure its got something to do with the javascript promise or it cant find the mongodb url but i havent been able to pinpoint the issue.我很确定它与 javascript 承诺有关,或者它找不到 mongodb url,但我无法查明问题。 I also have all the necessary packages installed.我还安装了所有必要的软件包。 Its my first time using node so any help would be great.这是我第一次使用 node,所以任何帮助都会很棒。

When using docker-compose you have to remember that each service is its own container.使用 docker-compose 时,您必须记住每个服务都是它自己的容器。 when your Node.js service is looking for localhost it is looking at itself.当您的 Node.js 服务正在寻找localhost 时,它正在寻找自身。

To fix this point mongoose at the MongoDB container by using its service name specified in your docker-compose: MONGODB_URI: mongodb://root:example@mongodb:27017/two?authSource=admin要使用MONGODB_URI: mongodb://root:example@mongodb:27017/two?authSource=admin -compose 中指定的服务名称在 MongoDB 容器中修复这一点MONGODB_URI: mongodb://root:example@mongodb:27017/two?authSource=admin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM