What is the process of inserting binary data into mongoDB along with an objectId?

I'm trying to add a document to a collection that requires an ObjectId and a BinData value, but I'm not sure how to do it.

When I attempt to execute this code, I receive the following 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 am using Meteor

Therefore, I can use

var ObjectId = Meteor.Collection.ObjectID;
. But I am unsure on how to access the BinData.

ReferenceError: BinData is not defined

Answer №1

Discovered this solution today too.

In addition to the previous response, utilizing ObjectID and Binary from the MongoDB driver can help resolve issues with binary data mismatches after insertion. The root cause lies in how the Binary function operates, requiring either a raw string or buffer input. To work around this, you can initialize a buffer from base64 encoded content like so:

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

async function execute() {
  // Establish connection with MongoDB 
  const client = new MongoClient()

  // Connect to the database
  await client.connect(...)

  try {
    // Insert base64 encoded content using ObjectID and Binary
    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 the client connection
    await client.close()
  }
}

Answer №2

Below is the sample NodeJS script for inserting data into a collection. Specifically for your question, here is the required statement when working with NodeJS.

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

Complete 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 require a pure JavaScript object of ObjectId, this library can be used.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bring JSON data into your MongoDB database

Recently, I've been working with a Python script that creates a large JSON file. After running the script, it generates a text file in Notepad containing the JSON data. I'm now looking to transfer this JSON data into a MongoDB database for storag ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

Developing asynchronous DOM functions for optimal performance

Imagine having a large amount of data that needs to be processed. In this scenario, the processing must happen on the client side rather than the server side. The data processing involves iterating through each element in the data set: for element in data ...

What could be causing the JSON String decode error to occur while utilizing extjs ajax?

Here is an example of my code: Ext.Ajax.request({ url:'test.jsp', params:{id:id,password:password}, success:function(response){ console.log(response); var results = Ext.util.J ...

Guide on organizing a series of links into an array

I'm looking to create a series of links: Using a for loop to generate these links, I want to store every x-th value into the photos[i] array. The code I have so far is not working as expected due to issues with string concatenation. My knowledge of J ...

Despite the value being true, the if statement does not work when used with a Mongoose object in Node.js

Currently working on a bidding app, Below is the schema for the bidding model const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, location: String, specilization: String, image: String, ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

Encountering issues with Spotify API when using axios to retrieve playlist tracks, leading to an undefined object response

import axios from "axios"; import React, {useState, useEffect} from "react"; export default function Dashboard({token}) { const [playlist_id, setPlaylistId] = useState([]); const [href, setHref] = useState([]); const [playlists, setPla ...

Incorporate a button into your Django formset application

Working with Django 5, I am in the process of creating a web application for managing a Secret Santa gift exchange project. One issue I'm facing is that formsets are not dynamic, meaning I cannot generate a variable number of forms based on user inpu ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

Alter the position of the anchor object in the center using JavaScript upon page load

When my page loads, I want to automatically jump to a specific anchor tag and ensure that the anchor object is centered in the window. Initially, I implemented a basic function to achieve this: <body onload="goToAnchor();"> <script type="text/ja ...

Getting Started with NodeJS Child Process for Electrons

My current challenge involves integrating a Gulp setup with debugging electron-quick-start. I am attempting to close and reopen Electron when changes are made to my source files using child_process.spawn. Launching the application seems to work fine, but w ...

Utilizing Unix timestamps for x-values while displaying dates as x-labels in an ECharts line chart

I'm struggling with incorporating date-converted unix timestamps as values in my ECharts graph. The x-axis of my chart is meant to display the recording time for each buy or sell price, represented by respective lines. Everything functions properly wh ...

Click to remove the parsed element

I'm working on a project with a parsed xml-file containing duplicate elements. I need to create a button that hides one of them when clicked using an onclick statement. Can someone help me achieve this? <!DOCTYPE html> <html> <body&g ...

What is the process for passing data to an HTML element using Express and NodeJs?

Is there a way to transfer data from a web or local file to an HTML element using Node.js/Express? Here is a snippet of what I am trying to achieve: Retrieve data from a source, parse it, and then send it to a specific element in index.html app.get("/", ( ...

Tips on organizing columns in Vue when sorting is needed for computed values

I have come across various resources for sorting data that is contained within an array, but I am unable to locate any information on how to sort dynamically generated data. <table> <thead> <tr> <th>Program</th& ...

Failed to fetch job details from the server at http://localhost:3000/api/jobdetail as it returned a

I'm currently working with a MongoDB database that has two collections: users and jobdetail. My goal is to establish a connection with the jobdetail collection and retrieve its data using the following app.js code: const express = require('expre ...

Adding and removing dynamic fields with Bootstrap functionality

Recently, I've been trying to develop a feature where users can add and remove fields by clicking on a button. However, I've encountered a roadblock in my progress. If you take a look at this CodePen link, you'll see what I have so far. My a ...

Display a badge in the navbar on specific VueJS pages

I have embarked on the journey of creating a single page application using Vue 3, and I've encountered an interesting scenario where I want to display a badge in the navigation bar for specific pages. This is how my setup looks: // App.vue <templat ...

Activate a link, launch a pop-up window, and navigate to the link within the pop-up

I have an unusual idea I'm working on. Let me explain the situation first, and then I'll outline the step-by-step process I want to follow. I currently have a list of items inside a <ul>. Whenever I click on one of these items, I want a mod ...