0

抽象的

将图像数据存储为 base64 编码字符串是可行的,但是当查看 Mongo 中的内容时,我保存的原始字符串只是结束持久字符串的前半部分。因为这个查询不起作用。

细节

考虑以下架构:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var imageSchema = new Schema({
    mime:  String,
    bin: String,
    uses : [{type: Schema.Types.ObjectId}]
});

module.exports = mongoose.model('Image', imageSchema);

bin现场,我存储 base64 图像数据。所以这个字符串可能很大(但是当它只有大约 40k 时,这个测试也会失败)。

更新

我做了进一步的分析,这个更新的测试块更好地显示了我看到的结果:

var buffer = getImageFromFileSystem();
var bin = buffer.toString('base64');
var i = new Image({
    mime : 'image/jpeg',
    bin : bin
});
i.save(function(err, image){
    if (err)
        console.log(err);
    console.log("=== original? "+(image.bin === bin)); //outputs true
    console.log("now find it by id and then compare again")
    Image.findOne({
        _id : image._id
    }, function(err, img) {
        if (err)
            console.log('crap error');
        if (img) {
            console.log('found one!: '+img.id+', lets compare... ');
            console.log("===? "+(img.bin === bin)); //outputs true again!
        }
    });
    //OK so clearly all is well, so let search by the bin str
    Image.findOne({
        bin : bin
    }, function(err, img) {
        if (err)
            console.log('crap error');
        if (!img) {
            console.log("none found") // we hit this... what the heck???
    });

所以我决定去数据库中查看该bin值。 在这里我看到它的值是我bin保存的原始字符串加上附加到它末尾的至少两倍的字符。所以我原来的base64字符串是存储在MongoDB中的值开头的子字符串。所以当我这样做时findOne({bin:myBinValue})不起作用,因为比较是在 Mongo 内部完成的。但是,如果我bin从 Mongo 检索值然后进行比较,它似乎会恢复到我的原始值,然后在我的应用程序中 javasript 比较是相同的!是什么赋予了!?我在这个领域没有索引。

> db.images.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "mydb.images",
                "name" : "_id_"
        }
]
4

0 回答 0