如何从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
最满意答案
您应该先将这些行添加到您的代码中:
use strict; use warnings;
他们将抓住潜在的错别字。 例如,
$inventaris
是与$inventory
不同的变量。 你真的有意要有两个变量吗? 很难从你的代码中知道。 同样,你真的有一个名为$naam
的变量吗?是的,可以从2个独立的子文件写入文件。 目前,
$name
是您的startNewOrder
子版本地。 一种让你的其他子文件可见的方法是在你的代码开始时声明它,使它在你的代码文件中是全局的。 你可以将你的format
移动到你write
的相同的子文件write
吗?最好使用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 yourstartNewOrder
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 yourformat
into the same sub as yourwrite
?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 ...
-
有没有一种工具可以从文件中自动提取常用的子程序?(Is there a tool to automatically extract common subroutines from files?)[2022-02-19]
您可以尝试使用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 ...
-
在perl中安排子程序(Schedule subroutines in perl)[2022-05-07]
重复的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 ...
-
我如何在Perl的不同子程序中写入相同的文件?(How can I write to the same file in different subroutines in Perl?)[2022-02-04]
您应该先将这些行添加到您的代码中: use strict; use warnings; 他们将抓住潜在的错别字。 例如, $inventaris是与$inventory不同的变量。 你真的有意要有两个变量吗? 很难从你的代码中知道。 同样,你真的有一个名为$naam的变量吗? 是的,可以从2个独立的子文件写入文件。 目前, $name是您的startNewOrder子版本地。 一种让你的其他子文件可见的方法是在你的代码开始时声明它,使它在你的代码文件中是全局的。 你可以将你的format移动到你write ... -
Perl:显示使用过的子程序(Perl: show used subroutines)[2022-03-12]
除了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: 在输入表单中添加一个隐藏的输 ...