通过Mongoid ORM将UTF8兼容字符串保存到MongoDB时,字符串无效UTF-8(BSON :: InvalidStringEncoding)

Ton*_*ony 4 ruby utf-8 mongodb bson mongoid

我使用Mongoid为我的ORM将数据从MySQL表导入MongoDB.尝试将电子邮件地址另存为字符串时出错.错误是:

/Library/Ruby/Gems/1.8/gems/bson-1.2.4/lib/../lib/bson/bson_c.rb:24:in `serialize': String not valid UTF-8 (BSON::InvalidStringEncoding)
    from /Library/Ruby/Gems/1.8/gems/bson-1.2.4/lib/../lib/bson/bson_c.rb:24:in `serialize'
Run Code Online (Sandbox Code Playgroud)

从我的GUI - 这是表信息的屏幕截图.您可以看到它以UTF8编码.

表信息

同样来自我的GUI - 这是我导入的MySQL表中字段的屏幕截图

mysql GUI中的数据是什么样的

当我从MySQL CLI获取数据时会发生这种情况.

mysql CLI中的数据是什么样的

最后,当我检查ruby对象中的数据时,我得到的内容如下所示: 检查了红宝石物体

我在这里有点困惑,因为无论我的表是UTF-8还是那个funky显然是有效的UTF-8字符作为双字节.任何人都知道我为什么会收到这个错误?

小智 6

尝试使用这个帮手:

http://snippets.dzone.com/posts/show/4527

它提出了一个方法utf8?在字符串上.所以你可以从mysql中获取String并查看它是否是utf8:

my_string.utf8?
Run Code Online (Sandbox Code Playgroud)

如果不是,那么您可以尝试使用其他方法更改String的编码:

my_string.asciify_utf8
my_string.latin1_to_utf8
my_string.cp1252_to_utf8
my_string.utf16le_to_utf8
Run Code Online (Sandbox Code Playgroud)

也许这个String在其中一个编码中保存在mysql上.