Mongoose& Mongoose与Mongo DB 4.0的交易快速的NodeJs [英] Mongo DB 4.0 Transactions With Mongoose & NodeJs, Express

查看:74
本文介绍了Mongoose& Mongoose与Mongo DB 4.0的交易快速的NodeJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中我将MongoDB用作应用程序层中带有Nodejs + Express的数据库,我有两个集合,分别是

I am developing an application where I am using MongoDB as database with Nodejs + Express in application layer, I have two collections, namely

  1. 用户
  2. 交易

在这里,我必须以一定数量更新成千上万个用户的钱包,如果成功创建了一个包含每笔交易相关信息的新文档,这是我的代码:

Here i have to update wallet of thousands of users with some amount and if successful create a new document with related info for each transaction, This is My code :

 userModel.update({_id : ObjectId(userId)}, {$inc : {wallet : 500}}, function (err, creditInfo) {
    if(err){
        console.log(err);                            
    }
    if(creditInfo.nModified > 0) {
        newTransModel = new transModel({
            usersId: ObjectId(userId),            
            amount: winAmt,         
            type: 'credit',           
        }); 
        newTransModel.save(function (err, doc) {
            if(err){
                Cb(err); 
            }
        });
    }                            
});

但此解决方案不是atomic,始终存在用金额更新用户钱包但未在交易收集中创建相关交易的可能性,从而导致财务损失.

but this solution is not atomic there is always a possibility of user wallet updated with amount but related transaction not created in transactions collection resulting in financial loss.

我听说最近MongoDB在其4.0 version中添加了Transactions支持,我已经阅读了MongoDB文档,但无法通过Node.js中的猫鼬成功地实现它 strong>,谁能告诉我如何使用MongoDB的最新Transactions功能(具有这些功能

I have heard that recently MongoDB has added Transactions support in its 4.0 version, I have read the MongoDB docs but couldn't get it to successfully implement it with mongoose in Node.js, can anyone tell me how this above code be reimplemented using the latest Transactions feature of MongoDB which have these functions

Session.startTransaction()
Session.abortTransaction()
Session.commitTransaction()

MongoDB文档:单击此处

MongoDB Docs : Click Here

推荐答案

在Node.js中使用猫鼬,谁能告诉我如何使用最新的交易功能重新实现以上代码

with mongoose in Node.js, can anyone tell me how this above code be reimplemented using the latest Transactions feature

要在 MongoDB多文档事务支持://mongoosejs.com/docs/guide.html"rel =" noreferrer>猫鼬,您需要的版本大于v5.2.例如:

To use MongoDB multi-documents transactions support in mongoose you need version greater than v5.2. For example:

npm install mongoose@5.2

猫鼬式事务方法返回一个Promise,而不是一个需要使用await的会话.参见:

Mongoose transactional methods returns a promise rather than a session which would require to use await. See:

  • Transactions in Mongoose
  • Blog: A Node.JS Perspective on MongoDB 4.0: Transactions

例如,更改以上资源和您的示例中的示例,您可以尝试:

For example, altering the example on the resource above and your example, you can try:

const User = mongoose.model('Users', new mongoose.Schema({
  userId: String, wallet: Number
}));
const Transaction = mongoose.model('Transactions', new mongoose.Schema({
  userId: ObjectId, amount: Number, type: String
}));

await updateWallet(userId, 500);

async function updateWallet(userId, amount) {
  const session = await User.startSession();
  session.startTransaction();
  try {
    const opts = { session };
    const A = await User.findOneAndUpdate(
                    { _id: userId }, { $inc: { wallet: amount } }, opts);

    const B = await Transaction(
                    { usersId: userId, amount: amount, type: "credit" })
                    .save(opts);

    await session.commitTransaction();
    session.endSession();
    return true;
  } 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; 
  }
}

不是原子的,总是有可能用金额更新用户钱包,但是未在交易收集中创建相关交易,导致财务损失

is not atomic there is always a possibility of user wallet updated with amount but related transaction not created in transactions collection resulting in financial loss

您还应该考虑更改MongoDB 数据模型.特别是如果两个集合是自然相连的.另请参见原子操作的模型数据以获取更多信息. .

You should also consider changing your MongoDB data models. Especially if the two collections are naturally linked. See also Model data for Atomic Operations for more information.

您可以尝试的示例模型是事件源模型.首先创建一个交易条目作为事件,然后使用聚合重新计算用户的钱包余额.

An example model that you could try is Event Sourcing model. Create a transaction entry first as an event, then recalculate the user's wallet balance using aggregation.

例如:

{tranId: 1001, fromUser:800, toUser:99, amount:300, time: Date(..)}
{tranId: 1002, fromUser:77, toUser:99, amount:100, time: Date(..)}

然后引入一个过程,根据需要(即每6个小时)计算每个时段内每个用户的数量作为缓存.您可以通过添加以下内容来显示当前用户的钱包余额:

Then introduce a process to calculate the amount for each users per period as a cache depending on requirements (i.e. per 6 hours). You can display the current user's wallet balance by adding:

  • 用户的最后缓存量
  • 自上次缓存的金额以来,该用户的任何交易都发生了.即0-6小时前.

这篇关于Mongoose& Mongoose与Mongo DB 4.0的交易快速的NodeJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆