Home > Back-end >  Mongoose can't connect (localhost)
Mongoose can't connect (localhost)

Time:12-11

I am trying to connect to my database using mongoose within Apollo-Server-Express. I have created a db in the terminal. I read that 'mongodb://localhost:27017/*db-name *' is the default uri-string that mongoose.connect takes as first argument.

However, console.log(mongoose.connection.readyState) prints out '2' - connecting. I would expect '1', right? When querying, the server freezes, and a ServerSelectionError gets thrown. I have tried prepending the mongoose.connect statement with await (as I saw in a tutorial) but then, the start-up process freezes. Is there anything fundamental that I am missing? Any help appreciated!!

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const mongoose = require('mongoose');

const main = async () => {
  const app = express();

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    introspection: true,
    playground: true,
  });

  await server.start();

  server.applyMiddleware({
    app,
  });

  mongoose.connect('mongodb://localhost:27017/db-name', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  });

  console.log(mongoose.connection.readyState);

  console.log('MongoDB connected!!');

  app.listen(process.env.PORT || 4000, () => {
    console.log(`           
  • Related