jdesboeufs / connect-mongo

MongoDB session store for Express
MIT License
1.96k stars 341 forks source link

^4.4.1 with Mongoose: UnhandledPromiseRejectionWarning: TypeError: con.db is not a function #416

Closed jmcombs closed 3 years ago

jmcombs commented 3 years ago

Attempt 1

(async () => {
  try {
    // Connect to MongoDB
    await mongoose.connect(mongoDbUrl, mongoDbOptions);
  } catch (err) {
    debug(err);
  }
})();

// Rename MongoDB Connection
const db = mongoose.connection;
!
// Using Express Session with Google Cloud Datastore to securly store session/cookie information
app.use(
  session({
    // Using MongoDB as session store
    store: MongoStore.create({
      client: dbConnection, // Use Mongoose for DB Conection
      ttl: 1800000, // Ages session out at 30 minutes
      autoRemove: 'native', // Uses MongoDB's native Time to Live (TTL) to expire and remove records
    }),
  }),
);

Attempt 2

// Define MongoDB connection parameters
const mongoDbOptions = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
};
const dbConnection = async () => {
  try {
    // Connect to MongoDB
    await mongoose.connect(mongoDbUrl, mongoDbOptions);
  } catch (err) {
    debug(err);
  }
};
dbConnection();
!
// Rename MongoDB Connection
const db = mongoose.connection;
!
// Using Express Session with Google Cloud Datastore to securly store session/cookie information
app.use(
  session({
    // Using MongoDB as session store
    store: MongoStore.create({
      client: dbConnection, // Use Mongoose for DB Conection
      ttl: 1800000, // Ages session out at 30 minutes
      autoRemove: 'native', // Uses MongoDB's native Time to Live (TTL) to expire and remove records
    }),
  }),
);

Both result in the same error (below). I have also tried clientPromise instead of client and the same error occurs. I want to keep my mongoose connection renamed to db which is why I have not gone with the example that uses a promise.

(node:3880) UnhandledPromiseRejectionWarning: TypeError: con.db is not a function
    at /workspace/node_modules/connect-mongo/build/main/lib/MongoStore.js:125:32
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3880) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3880) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
mingchuno commented 3 years ago

@jmcombs Did you try to take a look at this example yet? https://github.com/jdesboeufs/connect-mongo/blob/master/example/mongoose.js

jmcombs commented 3 years ago

@mingchuno, I did and I am not trying to use the Promise method. I am trying to use the async/await method which should work with the client option introduced in 4.3, should it not?

jmcombs commented 3 years ago

I separated out Mongoose from Express. This works well for me. Posting here as an example for anyone else to reuse.

dbService.js

const mongoose = require('mongoose');
const debug = require('debug')('app:core:db:service');
const chalk = require('chalk');

const mongoDbUrl = 'myMongoDbUrl'
const mongoDbOptions = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
};
(async () => {
  await mongoose
    .connect(mongoDbUrl, mongoDbOptions)
    .then(() => {
      debug(`Connected to ${chalk.green('MongoDB')}`);
    })
    .catch((err) => {
      debug(`${chalk.green('MongoDB')} connection ${chalk.red(`error`)}: ${err}}`);
    });
})();
const db = mongoose.connection;
db.on('error', (err) => {
  debug(`${chalk.green('MongoDB')} connection ${chalk.red(`error`)}: ${err}}`);
});
const dbClient = db.getClient();

module.exports = dbClient;

app.js

const MongoStore = require('connect-mongo');
const dbClient = require('dbService');

app.use(
  session({
    // Using MongoDB as session store
    store: MongoStore.create({
      client: dbClient, // Use Mongoose for DB Conection
      ttl: 1800000, // Ages session out at 30 minutes
      autoRemove: 'native', // Uses MongoDB's native Time to Live (TTL) to expire and remove records
      crypto: {
        secret: expressSessionSecret,
      },
    }),
  }),
);