Node.js / MongoDB / Mongoose:缓冲区比较 [英] Node.js / MongoDB / Mongoose: Buffer Comparison

查看:162
本文介绍了Node.js / MongoDB / Mongoose:缓冲区比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,一点背景:

我正在尝试检查图像的二进制数据是否已经保存在Mongo中。给定以下模式:

I'm trying to check to see if an image's binary data has already been saved in Mongo. Given the following schema:

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

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

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

...我想查询是否存在图像,如果它确实添加了一个引用我的对象正在使用它,然后更新它。如果没有,我想创建(upsert)它。

...I want to query to see if an image exists, if it does add a reference that my object is using it, and then update it. If it doesn't, I want to create (upsert) it.

鉴于它不存在的情况,下面的代码完美地运行。如果是,则以下代码不会,并将另一个Image文档添加到Mongo。我觉得它可能是Mongo Buffer类型与节点缓冲区的比较问题,但我无法弄清楚如何正确地比较它们。请让我知道如何更新以下内容!谢谢!

Given the case that it does not exist, the below code works perfectly. If it does, the below code does not and adds another Image document to Mongo. I feel like it is probably a comparison issue for the Mongo Buffer type vs node Buffer, but I can't figure out how to properly compare them. Please let me know how to update the below! Thanks!

Image.findOneAndUpdate({
    mime : contentType,
    bin : image
}, {
    $pushAll : {
        uses : [ myObject._id ]
    }
}, {
    upsert : true
}, function(err, image) {
    if (err)
        console.log(err);
    // !!!image is created always, never updated!!!
});


推荐答案

Mongoose将目标存储的缓冲区元素转换为mongodb < a href =http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html>二进制,但它在执行查询时执行适当的强制转换。
还会在单元测试(还存储和检索node.js缓冲区)。

Mongoose converts Buffer elements destined to be stored to mongodb Binary, but it performs the appropriate casts when doing queries. The expected behavior is also checked in units tests (also the storage and retrieval of a node.js Buffer).

您确定要传递node.js缓冲区吗?

Are you sure you are passing a node.js Buffer?

在任何情况下,我认为处理初始问题的最佳方法(检查图像是否已经在数据库中)将存储二进制文件的强哈希摘要(sha1,sha256,...)数据并检查(使用加密模块)。
查询时,作为初步测试,您还可以检查二进制长度以避免不必要的计算。

In any case I think the best approach to handle the initial problem (check if an image is already in the db) would be storing a strong hash digest (sha1, sha256, ...) of the binary data and check that (using the crypto module). When querying, as a preliminary test you could also check the binary length to avoid unnecessary computations.

有关如何获取图像摘要的示例在存储/查询之前:

For an example of how to get the digest for your image before storing/querying it:

var crypto = require('crypto');

...

// be sure image is a node.js Buffer
var image_digest = crypto.createHash('sha256');
image_digest.update(image);
image_digest = image_digest.digest('base64');

这篇关于Node.js / MongoDB / Mongoose:缓冲区比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆