草庐IT

javascript - 如何为 Mongoose 查询中返回的每个文档执行异步方法

coder 2023-10-28 原文

我有一个 mongoose 模型架构,设置如下。

var orderSchema = new Schema ({
 _invoices: [{ type: Schema.ObjectId, ref: 'invoice'},
 _discounts: [{ type: Schema.ObjectId, ref: 'discount'},
 _client: String

});

orderSchema.methods.totalInvoiced = function (cb) {
 this.populate('_invoices', function (err, order) {
  cb(err, _.reduce(_.pluck(order._invoices, 'amount'), function (a, b) {
    return a+b;
     }, 0);
     }

};

orderSchema.methods.totalDiscount = function (cb) {
  this.populate('_discounts', function (err, order) {
  cb(err, _.reduce(_.pluck(order.discounts, 'amount'), function (a, b) {
    return a+b;
     }, 0);
     }

};

现在我想获取订单集合,但我想将“totalInvoiced”和“totalDiscount”作为附加属性包含在返回集合中的每个文档中。我知道这可能是“totalInvoiced”成为虚拟属性(property)的情况,但我并不总是希望将其包括在内。这是我的尝试方法,但我觉得可能有更好的方法来做到这一点。

Order.find({}, function (err, orders) {
     // for each order calc totals and add to document as two new properties
     _.each(orders, function (order) {
       async.parallel({
         invoice: function (cb) {
           order.totalInvoiced(cb);
         },
         discount: function (cb) {
           order.totalDiscount(cb);
         }
       }, function (err, result) {
        order.totalInvoiced = result.invoice;
        order.totalDiscount = result.discount;
       }

     });

     return orders;

    });

我的问题是什么是对集合执行查询的最佳方式,同时作为查询的一部分在每个文档上执行一些异步方法,或者我通过迭代查询结果来执行此操作的方式正确的方法来做到这一点。也许使用查询流

最佳答案

_.each() 不是异步的,因此当所有总数都已填充时,您将很难继续执行。此外,如果您无法控制 Order.find() 将返回多少订单,那么如果您不使用限制来限制数量,您可能会遇到一些严重的性能问题。

你可以尝试这样的事情:

Order.find({}, function (err, orders) {
    // populate max 15 orders at any time
    async.mapLimit(orders, 15, function (order, cb) {
        async.parallel({
            invoice: function (cb) {
                order.totalInvoiced(cb);
            },
            discount: function (cb) {
                order.totalDiscount(cb);
            }
        }, function (err, result) {
            order.totalInvoiced = result.invoice;
            order.totalDiscount = result.discount;
            return cb(null, order);
        });
    }, function (err, orders) {
        console.log('Done!');
    });
});

关于javascript - 如何为 Mongoose 查询中返回的每个文档执行异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518635/

有关javascript - 如何为 Mongoose 查询中返回的每个文档执行异步方法的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. 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

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  6. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  9. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  10. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

随机推荐