首页 \ 问答 \ 如何从MongoDB聚合中读取未定义对象的属性?(How to read property of undefined object from MongoDB aggregation?)

如何从MongoDB聚合中读取未定义对象的属性?(How to read property of undefined object from MongoDB aggregation?)

我正在使用NodeJS / ExpressJS和MongoDB构建一个Treasure Hunt webapp,它由两个团队和用户组成。 每个用户都有个人分数,可以增加团队分数。 我想在仪表板视图中显示两个团队的总分数。 我使用MongoDB的Aggregation框架来查询db。 这是可以正常工作的代码并返回一个对象数组。

module.exports.getTotalTeamScore = function () {
   User.aggregate([
        { $group: {
            _id: "$team",
            total: { $sum: "$score"}
        }}
    ], function (err, results) {
        if (err) {
            console.error(err);
        } else {
            console.log(results);
            return results;
        }
    }
   );
}

我在用户模型文件中创建了此功能。 现在当我从某个路径文件中调用此函数时

var teamsObj = User.getTotalTeamScore();

它确实给出了如下的对象数组,但它是未定义的。

[ { _id: 'Team Black', total: 40 },
{ _id: 'Team Red', total: 60 } ]

问题是我无法在路径文件中做这样的事情。 (我可以在用户模型文件中访问它,其中存在getTotalTeamScore函数):

teamsObj[0].total

我得到的错误是TypeError: Cannot read property 'total' of undefined

请帮我解决这个问题。 我还是NodeJS / ExpressJS和MongoDB的新手,想学习。

谢谢


I am building a Treasure Hunt webapp using NodeJS/ExpressJS and MongoDB which comprises of two teams and users. Each user have individual score which add to team score. I want to display Total Score of both team on the dashboard view. I used MongoDB's Aggregation framework to query the db. Here is the code which works fine and returns an array of objects.

module.exports.getTotalTeamScore = function () {
   User.aggregate([
        { $group: {
            _id: "$team",
            total: { $sum: "$score"}
        }}
    ], function (err, results) {
        if (err) {
            console.error(err);
        } else {
            console.log(results);
            return results;
        }
    }
   );
}

I made this function in User model file. Now when I call this function from some route file by

var teamsObj = User.getTotalTeamScore();,

it does gives the array of objects as following however it is undefined.

[ { _id: 'Team Black', total: 40 },
{ _id: 'Team Red', total: 60 } ]

The problem is that I am unable to do something like this in route file. (I can access it fine inside the User model file where getTotalTeamScore function exists):

teamsObj[0].total

The error I get is TypeError: Cannot read property 'total' of undefined.

Please help me solve this problem. I am still new to NodeJS/ExpressJS & MongoDB and want to learn.

Thank you


原文:https://stackoverflow.com/questions/37290601
更新时间:2022-04-22 14:04

最满意答案

您应该先将这些行添加到您的代码中:

use strict;
use warnings;

他们将抓住潜在的错别字。 例如, $inventaris是与$inventory不同的变量。 你真的有意要有两个变量吗? 很难从你的代码中知道。 同样,你真的有一个名为$naam的变量吗?

是的,可以从2个独立的子文件写入文件。 目前, $name是您的startNewOrder子版本地。 一种让你的其他子文件可见的方法是在你的代码开始时声明它,使它在你的代码文件中是全局的。 你可以将你的format移动到你write的相同的子文件write吗?

在你的代码中,使用chomp而不是chop是更合适的。

最好使用exists来检查是否存在散列键,然后将它与undef返回的值进行比较。

use strict;
use warnings;

my $name = makeUniqueFileName();

# Sample data
my %inventory = (
    c1 => [ 1 .. 3 ],
    c2 => [ 4 .. 6 ]
);

addToOrder();

sub addToOrder { 
    print "give productcode:\n"; 
    my $code = <STDIN>; 
    chomp $code; 
    print "Give amount:\n"; 
    my $amount = <STDIN>;
    chomp $amount;
    if (not exists $inventory{$code}) {
        print "This product does not exist\n"; 
    }
    # etc...
}

我意识到我没有回答你所有的问题。 也许您可以一次专注于一个问题,并提供一个自包含的,可运行的示例,其中包含一小部分实际数据。 我经常通过将我的代码减少到一个仍然重现问题的最小示例来解决我自己的问题。


You should start by adding these lines to your code:

use strict;
use warnings;

They will catch potential typos. For example, $inventaris is a different variable from $inventory. Did you really mean to have two variables? It is hard to tell from your code. Similarly, do you really have a variable named $naam?

Yes, it is possible to write to a file from 2 separate subs. Currently, $name is local to your startNewOrder sub. One way to make it visible to your other sub is to declare it at the start of your code, making it global to your code file. Can you move your format into the same sub as your write?

In your code, it is more appropriate to use chomp instead of chop.

It is better to check for the existence of a hash key using exists than to compare it against the value returned by undef.

use strict;
use warnings;

my $name = makeUniqueFileName();

# Sample data
my %inventory = (
    c1 => [ 1 .. 3 ],
    c2 => [ 4 .. 6 ]
);

addToOrder();

sub addToOrder { 
    print "give productcode:\n"; 
    my $code = <STDIN>; 
    chomp $code; 
    print "Give amount:\n"; 
    my $amount = <STDIN>;
    chomp $amount;
    if (not exists $inventory{$code}) {
        print "This product does not exist\n"; 
    }
    # etc...
}

I realize I did not answer all of your questions. Perhaps you could focus on one question at a time, and provide a self-contained, runnable example with a small sample of actual data. I often solve my own problems by reducing my code to a minimal example which still reproduces the problem.

相关问答

更多
  • 是的,使用Perl本机版本( File::Copy和chmod() )总是更好。 原因有很多: 性能。 调用system()分支1到2个新进程(一个用于命令,可能另一个用于shell),这是一个繁重的操作 错误检查。 Perl中与IO相关的系统调用设置为"$!" 错误发生时的错误文本变量: File::Copy::copy($source, $destination) || die "Failed to copy from $source to $destination. Error: $!\n"; ...
  • 更改package Calc; package Calcu; 在Calcu.pm 软件包名称不匹配是给你带来麻烦的。 通过perldoc出口商了解血腥的细节。 查看perldoc perlootut ,了解perl中用于创建对象的不同方式的概述。 Change package Calc; to package Calcu; in Calcu.pm The mismatch in package names is what is giving you trouble. Have a read through ...
  • 您可以尝试使用PPI模块; 据我所知,你没有提到重构的工具。 You can try to use the PPI module; to my knowledge there's no tool for refactoring as the one you mentioned.
  • sub one { do 'verify1.pl'; } sub two { do 'verify2.pl'; } 但是,从长远来看,最好将脚本转换为模块,以便以现代和理智的方式管理复杂性。 sub one { do 'verify1.pl'; } sub two { do 'verify2.pl'; } In the long run, however, it is better to convert your scripts into modules in order ...
  • 重复的sleep调用会迅速发生,因为它们没有考虑创建JSON数据所花费的时间。 我也非常谨慎地使用system调用来进行数据操作,因为它必然会减慢速度,并且你可能会超出你想要的一秒响应时间。 在Perl中完成所有操作 我建议你看一下优秀的EV模块。 您需要定期事件类型 这是一个非常简短的例子。 你自己的回调子程序应该检查它被调用的时间,以确定要做什么,根据它是5秒,60秒等的倍数。或者你可以设置多个事件循环,每个间隔一个。 该模块使它非常直观 use strict; use warnings 'all'; ...
  • Ruby将Proc作为匿名的一流子程序对象。 可以通过将块传递给Proc::new , Kernel#proc或Kernel#lambda或者使用“stabby lambda”lambda文字语法来创建Proc::new 。 #!/usr/bin/env ruby # Make a reference to a subroutine codes = { one: -> { puts "This is code block one" puts "And this is code bloc ...
  • 您应该先将这些行添加到您的代码中: use strict; use warnings; 他们将抓住潜在的错别字。 例如, $inventaris是与$inventory不同的变量。 你真的有意要有两个变量吗? 很难从你的代码中知道。 同样,你真的有一个名为$naam的变量吗? 是的,可以从2个独立的子文件写入文件。 目前, $name是您的startNewOrder子版本地。 一种让你的其他子文件可见的方法是在你的代码开始时声明它,使它在你的代码文件中是全局的。 你可以将你的format移动到你write ...
  • 除了choroba的链接,您还可以使用分析器来显示调用的子程序(它们使用了多少次和多长时间): 剖析Perl Devel :: NYTProf - Profiling Perl代码 In addition to choroba's link, you can use a profiler to show what subroutines are called (how many times and how long they took): Profiling Perl Devel::NYTProf - Pr ...
  • 你可以使用Moose::MethodModifiers 。 我对Moose不太了解,但从手册中我可以看出你可以做到。 开始。 #!/usr/bin/perl -w use 5.010; use strict; use Moose; sub sub_one { say "I am sub one!"; } sub sub_two { say "Guess who!"; } # Note that the name of the function being modified isn't ...
  • 您的程序具有以下结构: sub new_user { if (param("Save")){ save(); } else { show_input_form(); } } if (param("New User")){ new_user(); } else { show_menu(); } 问题是输入表单没有设置pararm('New User') ,因此当您单击Save时,您不会在new_user结束。 解决方案1: 在输入表单中添加一个隐藏的输 ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)