These are chat archives for Automattic/mongoose

7th
Jul 2018
Gerald
@campanagerald
Jul 07 2018 13:41
hi guys

async function transfer(from, to, amount) {
const session = await Account.startSession();
session.startTransaction();
try {
const opts = { session, new: true };
const A = await Account.
findOneAndUpdate({ name: from }, { $inc: { balance: -amount } }, opts);
if (A.balance < 0) {
// If A would have negative balance, fail and abort the transaction
// session.abortTransaction() will undo the above findOneAndUpdate()
throw new Error('Insufficient funds: ' + (A.balance + amount));
}

const B = await Account.
  findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts);

await session.commitTransaction();
session.endSession();
return { from: A, to: B };

} catch (error) {
// If an error occurred, abort the whole transaction and
// undo any changes that might have happened
await session.abortTransaction();
session.endSession();
throw error; // Rethrow so calling function sees error
}
}

the example above only create a transaction on the same collections
how about for difference collections?
should i create sessions for each collection?
Kev
@lineus
Jul 07 2018 13:44
@campanagerald you create the session with either model and pass the same session into queries from either model. I think the fact that the session is started from a Model method makes it more confusing than it needs to be.
Gerald
@campanagerald
Jul 07 2018 13:45
i see, thanks
cosminn777
@cosminn777
Jul 07 2018 20:35
Hello, I try to exclude a filed in a nested object at select by using: '-_id -nestedobject.field', and it doesn't seem to work (retrieves without _id and with full nestedobject), am I doing this the right way?
*field
Kev
@lineus
Jul 07 2018 23:39
If the string doesn’t work @cosminn777 you could try to pass an object instead. Sorry I’m mobile at the moment or I’d test it. Something like ‘{ _id: 0, nestedObject: { field: 0 } }’