在perl中将MongoDB控制器项转换为JSON?
哪里有办法在perl中将MongoDB控制器项转换为JSON?,json,perl,mongodb,mojolicious,Json,Perl,Mongodb,Mojolicious,哪里有办法 using MongoDB; my $content = $db->items->find('something'); my $json; while($content->next){ push the data into a $json } 是否有任何方法可以将数据直接转换成json字符串 并将数据推到Mojolicous中 my @variables = $content->all; foreach (@variab
using MongoDB;
my $content = $db->items->find('something');
my $json;
while($content->next){
push the data into a $json
}
是否有任何方法可以将数据直接转换成json字符串
并将数据推到Mojolicous中
my @variables = $content->all;
foreach (@variables){
push the data into $json
}
为它编写了一个小的Mojo测试脚本。使用
$self->render(json => $json);
获取所有页面的列表,而不是迭代器。以下是测试:
$collection->find->all
输出:
#!/usr/bin/env perl
use Mojolicious::Lite;
use MongoDB;
# --- MongoDB preparation ---
my $conn = MongoDB::Connection->new; # create a MongoDB connection
my $test_db = $conn->test; # a MongoDB database
my $tests = $test_db->tests; # a test collection
# insert test objects
$tests->remove();
$tests->insert({name => 'foo', age => 42});
$tests->insert({name => 'bar', age => 17});
# --- Mojolicious::Lite web app ---
# access the tests collection in a mojoy way
helper mongo_tests => sub {$tests};
# list all tests as JSON
get '/' => sub {
my $self = shift;
$self->render(json => [$self->mongo_tests->find->all]);
};
# --- web app test ---
use Test::More tests => 6;
use Test::Mojo;
my $tester = Test::Mojo->new;
$tester->get_ok('/')->status_is(200);
my $json = $tester->tx->res->json;
is $json->[0]{name}, 'foo', 'right name';
is $json->[0]{age}, 42, 'right age';
is $json->[1]{name}, 'bar', 'right name';
is $json->[1]{age}, 17, 'right age';
注意:我无法使用
is_
测试$json
数据结构,因为MongoDB添加了OID。当您转储$json
+1时,您将看到它们。这是正确的方法,假设你想要所有的东西都同时出现。是的,工作很好,试着找出monogb控制器模型
1..6
ok 1 - get /
ok 2 - 200 OK
ok 3 - right name
ok 4 - right age
ok 5 - right name
ok 6 - right age