草庐IT

mongodb - mongoose 模型无法访问正在进行的事务的连接

coder 2023-10-28 原文

在我当前的 express 应用程序中,我想使用 mongodb 多文档事务的新功能。

首先指出我如何连接和处理模型很重要

我的 app.js(服务器)首先使用 db.connect() 连接到数据库。

我需要我的 db.index 文件中的所有模型。由于模型将使用相同的 Mongoose 引用启动,我假设 future 不同 route 模型的需求指向已连接和相同的连接。如果我对这些假设有任何错误,请纠正我。

我将连接引用保存在状态对象中,并在以后的事务需要时返回它

./db/index.ts

const fs       = require('fs');
const path     = require('path');
const mongoose = require('mongoose');

const state = {
 connection = null,
}

// require all models
const modelFiles = fs.readdirSync(path.join(__dirname, 'models'));
modelFiles
.filter(fn => fn.endsWith('.js') && fn !== 'index.js')
.forEach(fn => require(path.join(__dirname, 'models', fn)));

const connect = async () => {
  state.connection = await mongoose.connect(.....);
  return;
}

const get = () => state.connection; 

module.exports = {
 connect,
 get,
}

我的模型文件包含我需要的模式

./db/models/example.model.ts

const mongoose   = require('mongoose');
const Schema     = mongoose.Schema;
const ExampleSchema = new Schema({...);

const ExampleModel = mongoose.model('Example', ExampleSchema);
module.exports  = ExampleModel;

现在是我尝试进行基本交易的路线。 F

./routes/item.route.ts

const ExampleModel = require('../db/models/example.model');

router.post('/changeQty', async (req,res,next) => {

  const connection = db.get().connection;
  const session = await connection.startSession(); // works fine

  // start a transaction
  session.startTransaction(); // also fine

  const {someData} = req.body.data;

  try{

     // jsut looping that data and preparing the promises
     let promiseArr = [];
     someData.forEach(data => {
        // !!! THIS TRHOWS ERROR !!!
        let p = ExampleModel.findOneAndUpdate(
          {_id : data.id},
          {$incr : {qty : data.qty}},
          {new : true, runValidators : true}
        ).session(session).exec();
        promiseArr.push(p);
     })        

     // running the promises parallel
     await Promise.all(promiseArr);

     await session.commitTransaction();

    return res.status(..)....;

  }catch(err){
     await session.abortTransaction();
    // MongoError : Given transaction number 1 does not match any in-progress transactions.
    return res.status(500).json({err : err}); 
  }finally{
    session.endSession();
  }

})

但我总是得到以下错误,这可能与我的模型的连接引用有关。我假设,他们无权访问启动 session 的连接,因此他们不知道该 session 。

MongoError: Given transaction number 1 does not match any in-progress transactions.

也许我需要以某种方式在 db.connect 中使用直接连接引用启动模型?

某处犯了一个大错误,我希望你能引导我走上正确的道路。我感谢任何帮助,提前致谢

最佳答案

这是因为您正在并行执行操作:

所以你有一堆竞争条件。只需使用 async/await

让您的生活更轻松。

let p = await ExampleModel.findOneAndUpdate(
              {_id : data.id},
              {$incr : {qty : data.qty}},
              {new : true, runValidators : true}
            ).session(session).exec();

引用:https://github.com/Automattic/mongoose/issues/7311

如果这不起作用,请尝试一个接一个地执行 promise ,而不是 promise.all()

关于mongodb - mongoose 模型无法访问正在进行的事务的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768847/

有关mongodb - mongoose 模型无法访问正在进行的事务的连接的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  5. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  6. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  7. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  8. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  9. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  10. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

随机推荐