1
 using MongoDB;

 my $content = $db->items->find('something');
 my $json;
 while($content->next){
           push the data into a $json
 }

哪里有办法

 my @variables = $content->all;
 foreach (@variables){
    push the data into $json
 }

有什么办法可以直接将数据转换成json字符串;

并将数据推送到 Mojolicious

$self->render(json => $json);
4

1 回答 1

2

为它写了一个小的 Mojo 测试脚本。采用

$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';

输出:

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

注意:我不能is_deeply用来测试$json数据结构,因为 MongoDB 添加了 OID。当你转储时你会看到它们$json

于 2012-11-21T14:59:35.627 回答