Skip to content

Database connection module for Node.js applications using Mongoose.

License

Notifications You must be signed in to change notification settings

KTH/kth-node-mongo

Folders and files

NameName
Last commit message
Last commit date
Feb 12, 2025
Nov 6, 2024
Apr 14, 2021
Jan 4, 2022
Apr 15, 2021
Aug 1, 2023
Jan 3, 2022
Aug 31, 2016
Jan 3, 2022
Aug 1, 2023
Aug 18, 2021
Mar 1, 2025
Aug 1, 2024

Repository files navigation

@kth/mongo

Database connection wrapping Mongoose (for MongoDB)

This module connects to mongoDB using Mongoose default connection.

To use this module

Connect to database

  1. Import module
    const nodeMongo =require(@kth/mongo')

  2. Connect to mongoDB : nodeMongo.connect(options)

  3. Use Mongoose schema and model to interact with mongoDB

Function connect() returns a promise to be resolved upon completed connection or rejected on error.

Options

  • dbUsername (required) Credentials, the database user

  • dbPassword (required) Credentials, the password for the database user

  • dbUri (required) The URI for the mongoDb to connect to

  • logger (optional) A logger to use, defaults to stdout(console.log)

SSL(TLS) Options

  • ssl (optional) Boolean flag if database connection shoold be encrypted or not

Example without secure database connction

nodeMongo
  .connect({
    dbUsername: 'user',
    dbPassword: 'himligt',
    dbUri: 'mongodb://localhost/le_database?authSource=authDB',
    logger: log,
  })
  .then(() => log.debug('Connected to Mongo'))
  .catch(err => log.error(err))

Example with secure database connction

nodeMongo
  .connect({
    dbUsername: 'user',
    dbPassword: 'himligt',
    dbUri: 'mongodb://localhost/le_database',
    logger: log,
    ssl: true,
  })
  .then(() => log.debug('Connected to Mongo'))
  .catch(err => log.error(err))

Check status of connection

  1. Import module
    const nodeMongo =require('@kth/mongo')

  2. Check connection:

    if (nodeMongo.isOk()) {
      // OK
    } else {
      // ERROR
    }