我使用mongoose设置以下(简化和压缩)数据模型:
package Model::Tag;
use Moose;
use Mongoose::Class; with 'Mongoose::Document';
has 'value' => (is => 'rw', isa => 'Str', required => 1);
no Moose;
__PACKAGE__->meta->make_immutable;
package Model::Document;
use Moose;
use Mongoose::Class; with 'Mongoose::Document';
has 'title' => (is => 'rw', isa => 'Str', required => 1);
has_many 'tags' => (is => 'rw', isa => 'Model::Tag');
no Moose;
__PACKAGE__->meta->make_immutable;
我测试的重要部分是:
package main;
use strict;
use warnings;
use Data::Dumper;
my $expected; my $got;
my $doc = Model::Document->new(title => 'My new document with many tags');
my $tag1 = Model::Tag->new(value => 'foo');
my $tag2 = Model::Tag->new(value => 'bar');
my $x1 = $doc->tags->add($tag1);
my $x2 = $doc->tags->add($tag2);
# print "x1 = $x1 x2 = $x2 \n";
my $document_tags = $doc->tags;
print Dumper $document_tags;
can_ok($document_tags, 'all');
my $tag_array_ref = $document_tags->all();
现在出现问题:
$ document_tags的转储输出是一个Mongoose :: Join对象:
$VAR1 = bless( {
'delete_buffer' => {},
'with_class' => 'Model::Tag',
'buffer' => {
'58102804' => bless( {
'value' => 'foo'
}, 'Model::Tag' ),
'58069732' => bless( {
'value' => 'bar'
}, 'Model::Tag' )
}
}, 'Mongoose::Join' );
有关Mongoose::Join的文档列出了METHODS:
add, remove, find, find_one, first, all, hash_on, hash_array, query, collection, with_collection_name
但是打电话
$document_tags->all();
导致错误
Can't use an undefined value as a HASH reference at C:/Perl/site/lib/Mongoose.pm line 132.
有什么问题?
提前感谢您的帮助和想法。
答案 0 :(得分:0)
错误消息来自Mongoose,而不是您的测试程序。 Mongoose(0.23)的Mongoose.pm第132行是建立与MongoDB连接的方法。
在此之后,我注意到您的测试代码不包含对Mongoose->db()
的调用。这是指定要连接的数据库所必需的。在添加并尝试测试程序之后,我还注意到在尝试从中检索属性(即标记)之前,您的文档没有先保存到MongoDB。
这是您的测试代码,其中包含我为解决问题所做的更改。关键位以行# Connect to database
开头。
package Model::Tag;
use Moose;
use Mongoose::Class; with 'Mongoose::Document';
has 'value' => (is => 'rw', isa => 'Str', required => 1);
no Moose;
__PACKAGE__->meta->make_immutable;
package Model::Document;
use Moose;
use Mongoose::Class; with 'Mongoose::Document';
has 'title' => (is => 'rw', isa => 'Str', required => 1);
has_many 'tags' => (is => 'rw', isa => 'Model::Tag');
no Moose;
__PACKAGE__->meta->make_immutable;
package main;
use strict;
use warnings;
use Data::Dumper;
my $doc = Model::Document->new(title => 'My new document with many tags');
my $tag1 = Model::Tag->new(value => 'foo');
my $tag2 = Model::Tag->new(value => 'bar');
my $x1 = $doc->tags->add($tag1);
my $x2 = $doc->tags->add($tag2);
my $document_tags = $doc->tags;
print Dumper $document_tags;
# Connect to database
Mongoose->db('foo');
# and save our document first
$doc->save();
# now we can retrieve the array (note, not array ref) of tags
my @tag_array = $document_tags->all();
print Dumper(\@tag_array);