Mongoose 在 Apollo-Express 服务器上抛出错误 ECONNREFUSED

Posted

技术标签:

【中文标题】Mongoose 在 Apollo-Express 服务器上抛出错误 ECONNREFUSED【英文标题】:Mongoose throws error ECONNREFUSED on Apollo-Express server 【发布时间】:2021-04-15 02:41:55 【问题描述】:

如果这个问题是愚蠢或愚蠢的,我很抱歉,请指出正确的方向,非常感谢每一点帮助。

我目前正在使用 expressmongoose 构建 Apollo-Server。我让服务器使用 GraphQL 运行,但在使用 mongoose 连接后,它看起来像这样:

const express = require("express");
const  ApolloServer, gql  = require("apollo-server-express");
const fs = require("fs");

const port = 4000;
const path = "/graphql";

const app = express();

const typeDefs = gql(fs.readFileSync("./schema.graphql",  encoding: "utf8" ));

const resolvers = require("./resolvers");

const mongo = require('./config');
const  User  = require('./models');

const server = new ApolloServer(
  typeDefs,
  resolvers,
);

server.applyMiddleware( app, path );

app.listen(port, () => console.info(`Server started on port $port`));

将此作为我的配置:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const url = 'mongodb://localhost:27017/graphql';
const options = 
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true,
;

//mongoose.connect(url, options);
//mongoose.connection.once('open', () => console.log("Connected to mongoDB at $url"));

var connectWithRetry = function () 
  return mongoose.connect(url, options, function (err) 
    if (err) 
      console.error(
        "Failed to connect to mongo on startup - retrying in 5 sec\n\n",
        err
      );
      setTimeout(connectWithRetry, 5000);
    
    mongoose.connection.once("open", () =>
      console.log(`Connected to mongo at $Constants.mongodbUrl`)
    );
  );
;

connectWithRetry();

这应该可以正常工作吗? 但是当我打电话给npm start server.js 时,我收到以下错误:

npm start server.js

> start
> node server.js "server.js"

Server started on port 4000
Failed to connect to mongo on startup - retrying in 5 sec MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at NativeConnection.Connection.openUri (/Users/myUsername/newServer/server/node_modules/mongoose/lib/connection.js:832:32)
    at /Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:345:10
    at promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
    at Mongoose._promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:1135:10)
    at Mongoose.connect (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:344:20)
    at connectWithRetry (/Users/myUsername/newServer/server/config.js:16:19)
    at Object.<anonymous> (/Users/myUsername/newServer/server/config.js:30:1)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/Users/myUsername/newServer/server/server.js:14:15)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) 
  reason: TopologyDescription 
    type: 'Unknown',
    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
  

如果你需要我安装的 npm-packages:

graphql-node-server@ /path/server
├── apollo-server@2.19.1
├── express@4.17.1
├── graphql@15.4.0
├── mongodb@3.6.3
├── mongoose@5.11.11
└── nodemon@2.0.7

【问题讨论】:

代码对我来说看起来不错。确保 Mongodb 正在您的本地计算机上运行,​​因为这是唯一的情况。 这是我的问题之一,我没有写...我怎么办? 天哪,太尴尬了,我以为猫鼬会为我启动这个过程。如果您想手动回答,我很乐意给您正确答案 是的,您需要启动该服务。我确实从我的最后检查了它,你的代码对我来说工作正常。 是的,它有时会这样做,我查看了启动 mongoldb 进程的命令,我工作得很好。 【参考方案1】:

您需要在运行代码之前启动 MongoDB 服务。如果它没有运行,那么它将处于尝试重新连接的连续循环中。

同样,当它被连接时,open 事件将不会被触发。你需要把它移到你的连接函数之外,所以它应该是这样的。

var connectWithRetry = function () 
    return mongoose.connect(url, options, function (err) 
        if (err) 
            console.error(
                "Failed to connect to mongo on startup - retrying in 5 sec\n\n",
                err
            );
            setTimeout(connectWithRetry, 5000);
        
    );
;
mongoose.connection.once("open", () =>
    console.log(`Connected to mongo at $url`)
);

connectWithRetry();

【讨论】:

【参考方案2】:

我的错误是,我需要手动启动 mongoDB 进程。如果您没有,请重新启动它,对我来说解决了这个问题。

mongod --config /usr/local/etc/mongod.conf --fork

【讨论】:

以上是关于Mongoose 在 Apollo-Express 服务器上抛出错误 ECONNREFUSED的主要内容,如果未能解决你的问题,请参考以下文章

在 Mutation 中使用 GraphQL Args 属性

在 @nestjs/mongoose 中设置 mongoose 全局选项

在多个文件中使用 Mongoose Schema (mongoose)

在 Mongoose 中创建外键关系

Mongoose:无法在 Mongoose 数组 SchemaType 中添加一项。虽然可以添加不止一个

在导出的 Mongoose 模型中使用 Mongoose 模式函数