Promise { <Pending> } when attempting to connect to a MongoDB database

102 Views Asked by At

Following a tutorial I have this:

import {MongoClient} from "mongodb";

const user = "user_001";
const password = "imagineTheRealPassHere";
const cluster = "cluster0.unkpm";

const url = `mongodb+srv://${user}:${password}@${cluster}.mongodb.net/test?retryWrites=true&w=majority`;

export const connectDatabase = async () => {
    const client = await MongoClient.connect(url, {useNewUrlParser: true, useUnifiedTopology: true});

    const db = client.db('main');

    return {
        listings: db.collection('test_listings')
    };
};

and this is how it looks in Atlas: enter image description here

notice in the connection string we have mongodb.net/test. I am not sure about "test" . It should be

<db_name>

so I think it should be "main" then? But I did try "main" too and still same problem.

Anyway, then on the express side I have this:

import express, {Application} from 'express';
import {ApolloServer} from "apollo-server-express";
import {typeDefs, resolvers} from "./graphql/index";
import {connectDatabase} from "./database";

const port = 9000;

const mount = async (app: Application) => {
    const db = await connectDatabase();
    const server = new ApolloServer({typeDefs, resolvers, context: () => db});
    server.applyMiddleware({app, path:"/api"});

    app.listen(port);

    console.log('Fraiser is listening.');

    const listings = db.listings.find({}).toArray();
    console.log(listings);
};

mount(express());

But when I run the application, instead of seeing the contents of table_listings table, it just says: Promise { }

I think something in my connection is wrong but I am new and not sure what else to look at.

0

There are 0 best solutions below