Home > Blockchain >  mongodb connection db is undefined with mongoose
mongodb connection db is undefined with mongoose

Time:03-29

I am connecting using Mongoose using the following way

import { createConnection } from 'mongoose';
this.m_context = createConnection('mongodb://localhost/master')

But when I try to access this.m_context.db it is giving me undefined.

What am I doing wrong here? I checked the connection string that is working fine in the compass.

CodePudding user response:

What I found is, createConnection doesn't open connection and because of that, it was giving undefined, as it gives connection DB info only if the connection is open.

this.m_context = await new Promise<Connection>((resolve) => {
        createConnection('mongodb://localhost/master', undefined, (error, result) => {
          resolve(result)
        });
      });
  • Related