@moblybr/node-mongo-db
v1.5.0
Published
Mongodb connection package
Downloads
6
Keywords
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