如何将带有objectId的二进制数据添加到mongoDB? [英] How to add binary data with objectId to mongoDB?

查看:149
本文介绍了如何将带有objectId的二进制数据添加到mongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文档插入具有ObjectIdBinData值的集合中.因此,我不知道如何插入它.

I need to insert a document into a collection, which has an ObjectId and a BinData value. Therefore I don't know how to insert it.

使用此代码,我得到错误TypeError: Cannot read property 'ObjectId' of undefined.

With this code I get the error TypeError: Cannot read property 'ObjectId' of undefined.

server/fixtures.js

var ObjectId = Mongo.ObjectID;
var chunk = {
            "_id"     : ObjectId("57a9be3c89c1e4b50c574e3a"),
            "files_id": ObjectId("5113b0062be53b231f9dbc11"),
            "n"       : 0,
            "data"    : BinData(0, "/9j/4AAQSkZJRgA...and...so...on../2Q==")
        };

db.mediafiles.chunks.insert(chunk);


更新

我正在使用流星

因此,我可以使用var ObjectId = Meteor.Collection.ObjectID;.但是我怎么得到BinData?

Therefore I can use var ObjectId = Meteor.Collection.ObjectID;. But how do I get the BinData?

ReferenceError: BinData is not defined

推荐答案

今天也偶然发现了这一点.

Stumbled upon this today as well.

作为提到的其他答案,您可以使用MongoDB驱动程序提供的ObjectIDBinary.我遇到的问题是,插入后二进制数据不是我期望的,这是由于Binary函数的内部工作所致.它需要一个未编码的字符串或一个缓冲区,可以从base64编码的内容中初始化它,如下所示:

As the other answer mentioned you can use ObjectID and Binary provided by the MongoDB driver. The issue I had was that the binary data was not what I expected after inserting and this is due to the inner workings of the Binary function. It requires either an unencoded string or a buffer, which can be initialized from base64 encoded content like this:

const { Binary, ObjectID } = require('mongodb')

async function run() {
  // Configure MongoDB connection
  const client = new MongoClient()

  // Connect to MongoDB
  await client.connect(...)

  try {
    // Insert data using base64 encoded content and 
    // both ObjectID and Binary from mongodb package
    await client.db().mediafiles.chunks.insert({
      _id: ObjectID('57a9be3c89c1e4b50c574e3a'),
      files_id: ObjectID('5113b0062be53b231f9dbc11'),
      n: 0,
      data: Binary(Buffer.from('/9j/4AAQSkZJRgA...and...so...on../2Q==', 'base64')),
    })
  } finally {
    // Close client if it was opened
    await client.close()
  }
}

这篇关于如何将带有objectId的二进制数据添加到mongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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