npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@moblybr/node-mongo-db

v1.5.0

Published

Mongodb connection package

Downloads

6

Readme

@mobly/packages/node/mongo-db

Package with mongoDB connection for mobly projects

Pacote de conexão mongodb

Instalação

Para instalar o pacote:

npm i @moblybr/node-mongo-db

Uso

Para criar uma conexão com um banco de dados mongodb importe o método createConnection do pacote

import { createConnection } from '@moblybr/node-mongo-db' // es6

// ou //

const { createConnection } = require('@moblybr/node-mongo-db') // commonJs

createConnection(uri, config)

O método createConnection recebe dois parametros um uri e config

uri é a uri de conexão com seu banco de dados seja local ou remoto, se a uri for omitida por padrão ele busca uma uri em:

process.env.MONGO_URI

O segundo parametro config é um objeto de configurações para a conexão para saber mais sobre as configurações de conexão consulte as opções na documentação do mongoose em Mongoose Connecting to MongoDB por padrão o objeto de configurção a seguir é usado

{
  useNewUrlParser: true,
  reconnectTries: Number.MAX_VALUE,
  reconnectInterval: 1000,
  bufferCommands: false,
  bufferMaxEntries: 0,
  keepAlive: true
}

A seguite mensagem deve aparecer em seu console caso a conexão seja bem sucedida

Mongo connected

Usando transactions

O pacote também conta com transactions.

Start Session

Para iniciar uma transação, é necessário iniciar uma sessão com o startSession():

import { startSession } from '@moblybr/node-mongo-db' // es6

const session = startSession()

Usando a sessão

Você pode contar com 2 métodos diferentes para indicar o começo de uma transaction:

  • Helper withTransaction()
  • startTransaction()

withTransaction()

É o método recomendado para efetuar uma transaction devido ao retry automático e por lidar com os passos de commitar ou abortar a transação, bem como lidar com eventuais erros de rede entre shards do banco.

Exemplo:


import { createConnection, startSession } from '@moblybr/node-mongo-db'
import { Types } from 'mongoose'
import Privilege from '../../../../database/mongoose/Models/Privileges'
import ProfilePrivilege from '../../../../database/mongoose/Models/ProfilePrivilege'

  const delete = async () => {
    const idPrivilege = 1
    await createConnection()
    const session = await startSession()
    //  Aqui withTransaction recebe uma função assíncrona contendo as queries
    // commit e abort são tratados automaticamente e exceptions são propagados
    await session.withTransaction(async () => {
      if (!Types.ObjectId.isValid(idPrivilege)) {
        throw new CreateError(422, 'Id invalido!')
      }

      // Checa se o privilegio existe na Privileges
      const privilegeData = await Privilege.findOne({ _id: idPrivilege }).lean()

      const deleteProfilePrivilegeReturn = await ProfilePrivilege.deleteMany(
        { 'privilege._privilege': idPrivilege },
        { session }
      )

      // Ao fim deletar o privilegio da tabela raiz
      const deletePrivilegeReturn = await Privilege.deleteOne(
        { _id: idPrivilege },
        { session }
      )

      session.endSession()
    })
  } 

Preste bastante atenção:

Nas queries é necessário passar a session como segundo atributo, num objeto. Ao fim dos procedimentos, é necessário fechar a sessão.

startTransaction()

De forma similar, você iniciar uma transação sem a necessidade de passar uma função assíncrona como argumento, usando o session.startTransaction().
Desta forma é necessário commitar ou abortar a transaction explicitamente:


import { createConnection, startSession } from '@moblybr/node-mongo-db'
import Privilege from '../../../../database/mongoose/Models/Privileges'

const delete = async () => {
  await createConnection()
  const session = await startSession()

  try{
    await session.startTransaction()

    const deletedPrivilege = await Privilege.delete('myId', {session})
    await session.commitTransaction()
  }catch (e){
    await session.abortTransaction()
  }
    await session.endSession()
}

Note: É sempre necessário encerrar a sessão ao fim da transaction.

Fechando a conexão

Para encerrar a conexão ao banco de dados primeiro importamos o método closeConnection

import { closeConnection } from '@moblybr/node-mongo-db' // es6

// ou //

const { closeConnection } = require('@moblybr/node-mongo-db')  // commonJs

E depois é so chamar o mesmo para encerrar a conexão

closeConnection()

Isso abortará sua conexão ao banco de dados te dando uma resposta como esta em seu console

Mongo has disconnected