Clebo Sevic
Clebo Sevic

Reputation: 673

Mongoose throws error ECONNREFUSED on Apollo-Express server

I am sorry if this question is stupid or dumb, please just point me in the right direction, every bit of help is greatly appreciated.

I am currently building a Apollo-Server using express and mongoose. I got the server running with GraphQL, but after connecting it with mongoose, which looks like this:

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}`));

with this as my config:

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();

This is supposed to work right? But when i call npm start server.js i get the following error:

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
  }
}

If you need my installed npm-packages:

graphql-node-server@ /path/server
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Upvotes: 1

Views: 325

Answers (2)

Hamza Anis
Hamza Anis

Reputation: 2565

You need to start the MongoDB service before running your code. If it is not running then it will be on a continuous loop trying to reconnect.

Also when it is connected the open event will not be triggered. You need to move it outside of your connection function so it should be like this.

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();

Upvotes: 1

Clebo Sevic
Clebo Sevic

Reputation: 673

My mistake was, that i needed to start the mongoDB process manually. If you did not, start it an rerun it, for me that fixed the issue.

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

Upvotes: 0

Related Questions