#node.js #mongoose #transactions
Вопрос:
Я пытаюсь использовать транзакцию мангуста для работы с несколькими документами с node.js и это не работает
У меня много моделей, и я хотел бы внести некоторые обновления в базы данных в разных моделях данных.
Во-первых, я получаю данные, Во-вторых, я обновляю и сохраняю, В-третьих, я обновляю другую модель, в-четвертых, и в конце я делаю еще одно обновление в другой модели
Проблема в том, что после первого обновления ничего не происходит
import User from '../../models/user'
import Caso from '../../models/caso'
import Pessoa from '../../models/pessoa'
import Ocorrencia from '../../models/ocorrencia'
import Organizacao from '../../models/organizacao'
import Embarcacao from '../../models/embarcacao'
import Aeronave from '../../models/aeronave'
import Documento from '../../models/documento'
const getEntity = {
caso: (id, session) => Caso.findById(id, {session}),
pessoa: (id, session) => Pessoa.findById(id, {session}),
organizacao: (id, session) => Organizacao.findById(id, {session}),
ocorrencia: (id, session) => Ocorrencia.findById(id, {session}),
embarcacao: (id, session) => Embarcacao.findById(id, {session}),
aeronave: (id, session) => Aeronave.findById(id, {session}),
documento: (id, session) => Documento.findById(id, {session})
}
//Remove all card relation from its coin relation entity
const pullEntityCoin = {
caso: ({id, entity, session}) => Caso.updateMany({}, {$pull: {[entity]: id}}, {session}),
pessoa: ({id, entity, session}) => Pessoa.updateMany({}, {$pull: {[entity]: id}}, {session}),
organizacao: ({id, entity, session}) => Organizacao.updateMany({}, {$pull: {[entity]: id}}, {session}),
ocorrencia: ({id, entity, session}) => Ocorrencia.updateMany({}, {$pull: {[entity]: id}}, {session}),
embarcacao: ({id, entity, session}) => Embarcacao.updateMany({}, {$pull: {[entity]: id}}, {session}),
aeronave: ({id, entity, session}) => Aeronave.updateMany({}, {$pull: {[entity]: id}}, {session}),
documento: ({id, entity, session}) => Documento.updateMany({}, {$pull: {[entity]: id}}, {session})
}
//Add all coin relation entity to each entity relation
const pushEntityCoin = {
caso: ({id, entity, ids, session}) => Caso.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
pessoa: ({id, entity, ids, session}) => Pessoa.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
organizacao: ({id, entity, ids, session}) => Organizacao.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
ocorrencia: ({id, entity, ids, session}) => Ocorrencia.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
embarcacao: ({id, entity, ids, session}) => Embarcacao.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
aeronave: ({id, entity, ids, session}) => Aeronave.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session}),
documento: ({id, entity, ids, session}) => Documento.updateMany({_id: { $in: ids}}, {$push: {[entity]: id}}, {upsert: true }, {session})
}
const updateEntityCoin = async (_, { entityCoinInput }, { req }) => {
const { _id, entity, coin, ids } = entityCoinInput
console.log(entityCoinInput);
if (!req.isAuth) {
throw new Error('Unauthenticated user!')
}
const session = await db.startSession()
try {
await session.withTransaction(async () => {
const creator = await User.findById(req.userId, { session })
if (!creator) throw new Error('Usuário inexistente!')
const card = await getEntity[entity](_id, session)
if (!card) throw new Error('Caso não encontrado!')
//Remove all ids from coin node and includes the new coin array
card[coin] = ids
card.logs.push({
ordem: new Date().toISOString(),
_id: req.userId
})
await card.save({session})
var res = await pullEntityCoin[coin]({id: _id, entity, session })
console.log({res});
res = await pushEntityCoin[coin]({id: _id, entity, ids, session })
console.log({res});
const exists = creator[entity].find(
(id) => id.toString() === _id.toString()
)
if (!exists) {
creator[entityCoinInput.entity].push(entity)
await creator.save()
}
await session.commitTransaction()
})
// console.log(entity)
} catch (err) {
await session.abortTransaction()
throw err
} finally {
await session.endSession();
}
}
module.exports = {
Query: {},
Mutation: {
updateEntityCoin
}
}