How to add binary data with objectId to mongoDB?

夙愿已清 提交于 2019-12-11 06:59:04

问题


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.

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);

Update

I'm using Meteor

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

ReferenceError: BinData is not defined


回答1:


Here is the NodeJS code to insert data into collection. To answer your question specifically, you need the below statement if you are using NodeJS.

var ObjectId = require('mongodb').ObjectID;

Full NodeJS code (assuming you are using NodeJS):-

var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;

var bindata = new require('mongodb').Binary("ZzEudm1s");

var insertDocument = function(db, callback) {
    var chunk = {
        "_id" : new ObjectId("535e1b88e421ad3a443742e7"),
        "files_id" : new ObjectId("5113b0062be53b231f9dbc11"),
        "n" : 0,
        "data" : bindata
    };

    db.collection('Day1').insertOne(chunk, function(err, result) {
        assert.equal(err, null);
        console.log("Inserted a document into the collection.");
        callback();
    });
};

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    assert.equal(null, err);
    insertDocument(db, function() {
        db.close();
    });
});

If you need a pure JavaScript object of ObjectId, you can use the below library.

https://www.npmjs.com/package/objectid-purejs



来源:https://stackoverflow.com/questions/38850650/how-to-add-binary-data-with-objectid-to-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!