Search code examples
mongodbperlmojolicious

perl mojolicious mango driver: utf-8 characters not written correctly into mongodb


Anybody with mojolicious mango(https://metacpan.org/pod/Mango) knowledge can tell me how do you insert utf-8 characters into mongodb. Or maybe is this missing feature of the mango?

Thanks.


Solution

  • Mango has no issue with utf8 strings. I use them all the time. Your problem must lie elsewhere.

    In the following example, Mojo::Base implicitly imports the utf8 pragma, which tells perl to treat all strings in the source code as utf8. Also, before printing text to the console, i tell perl to use the utf8 IO layer on stdout, otherwise it won't print correctly. Note that you could use the :raw IO layer instead and it would work just as well.

    use Mojo::Base -strict;
    use Mango;
    
    sub mango { state $m = Mango->new }
    sub coll  { mango->db('test')->collection('utf8') }
    
    my $text = "utf8 is not so hard 😌";
    
    my $oid = coll->insert({ text => $text });
    my $doc = coll->find_one($oid);
    binmode(STDOUT, ":utf8");
    say $doc->{text};