The error message "Unable to instantiate grid.mongo.ObjectID" indicates that grid.mongo.Object

I have been working on implementing a JS code for my Next.js API that involves storing images in MongoDB GridFS and retrieving them via a simple API route. The snippet you see is from a file that is imported into the API route.

import { MongoClient } from "mongodb"
import Grid from "gridfs-stream"

const { MONGODB_URI, MONGODB_DB } = process.env

if (!MONGODB_URI) {
  throw new Error(
    "Please define the MONGODB_URI environment variable inside .env.local"
  )
}

if (!MONGODB_DB) {
  throw new Error(
    "Please define the MONGODB_DB environment variable inside .env.local"
  )
}

let cached = global.mongo

if (!cached) {
  cached = global.mongo = { conn: null, promise: null }
}

export async function connectToDatabase(dbIndex = 0) {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }

    cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
      const db = client.db(MONGODB_DB.split(",")[dbIndex])
      const grid = Grid(db, MongoClient)
      // Removed grid.collection("fs.files") as it caused an error
      return {
        client,
        db: db,
        gfs: grid
      }
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

While attempting to use createReadStream, I encountered the following error:

TypeError: grid.mongo.ObjectID is not a constructor

The problem seems to be related to

const grid = Grid(db, MongoClient)
but unfortunately, I'm unsure about how to resolve it. Any assistance on this matter would be highly appreciated.

Edit: Resolved the issue by removing grid.collection.

Answer №1

It has been advised to discontinue using grid fs stream as it is no longer necessary in the latest mongoDB versions. The recommended alternative is to use GridFSBucket.

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

Leveraging $regex within the MongoDB aggregation framework when utilizing $group操作

Here is an example to consider: db.article.aggregate( { $group : { _id : "$author", docsPerAuthor : { $sum : 1 }, viewsPerAuthor : { $sum : "$pageViews" } }} ); This code snippet groups by the author field and calculates two fields. ...

Show the HTML code within the form with the identifier html-editor-form

I have four different sections which are displayed when the corresponding icon is clicked. The area labeled as visual-editor contains multiple HTML values. I am looking to showcase all the HTML values within the visual-editor class under the html-editor ...

How to access Bootstrap's modal initial data-* upon closing

When displaying a bootstrap modal, a convenient method to retrieve associated data is by using the following code snippet: $('#myModal').on('show.bs.modal', function (e) { var id = $(e.relatedTarget).data('id'); alert( ...

Tips for adding a "dynamic" backdrop in THREE.js

I stumbled upon this website: Notice how the gradient background changes with a 360 degree shading effect as you move the camera. Which aspect of THREE.js would be responsible for creating something like this? Could someone provide guidance on where to ...

Is it possible to implement a modal within my API services?

Hello, I am in need of assistance. I am looking to display a modal every time my API returns an error. Can someone please help me figure out how to achieve this? I am currently using React hooks. const restService = (path, responseType = 'json') ...

passing a PHP variable into an HTML input field

Recently, I've encountered a problem where I need to transfer PHP variables to HTML input fields. echo $ManuellTagnavnMain; for ($n = 0; $n < 6; $n++) { print_r(++$ManuellTagnavnMain.PHP_EOL); } I'm looking for a way to pass these values ...

What steps can be taken to resolve the following issue: "name": "ValidatorError", "message": "Path `Name` must be provided."

I am encountering an issue while trying to fetch data from the client side with a post request. I am a beginner in MongoDB and Node.js and would appreciate any help in resolving this error. I am unsure of why this error is occurring, so any assistance woul ...

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

The count of records in MongoDB by the current month

Recently delving into MongoDB, I found myself in need of a way to retrieve the count of posts made in the current month. Keeping timestamps true in my PlateModel model, it appears as follows: { timestamps: true } The current code snippet in my Controller ...

Inheritance of nested directives in Angular.js

Click here for a live example I'm trying to understand how 00B can be contained within 00A. Here is the code snippet: <div directive-one="['foo', 'bar']"> <directive-two /> </div> In this code, the directi ...

Updating website links in real time with the power of jquery

Is there a way to dynamically change the parameter of a link? For example: Link1 Link2 Link3 By default, their URL is ?item=text, so link1 would be href="?item=link1", etc. But when I click on link1, the URLs of link2 and link3 should change to include ...

"Encountering issues with the callback function not being returned in node

Currently, I am leveraging the node AMQP module to establish a connection with RabbitMQ. The process includes successfully connecting, setting up an exchange, queue, and sending messages to the exchange, which can be verified on the management console. Ho ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

What is the best way to generate a new object within a function and then return it

The function performs the following steps: Retrieves an XML document through AJAX. Identifies relevant information within the document. Dynamically converts it into an object using a for loop. How can I access this generated object outside of the functi ...

Converting SQL filter queries to MongoDB in .NET

I'm facing a challenge with converting a basic query from SQL to Mongo, here's the original SQL code: select top(1)* from x where(a = 5) and(b = 6) and (c = 11) order by d desc This is what I have attempted so far: var builder = Builders<Bs ...

The Next.js router translates query parameters into encoded format when using the router.push

I'm attempting to create a redirect using router.push in order to include a query string. However, when I try to pass a special character like a comma as part of the parameter value, it encodes my URL. Can you actually include ',' in a URL u ...

Is altering the title of a service employee on your mind?

I'm curious about the consequences of renaming a service worker from sw.js to service-worker.js. Even after the rename, the old one is not found but somehow still showing the cached version. How long does it take for the new renamed service worker to ...

Encountered an issue while attempting to retrieve data from the HTTP URL

I encountered an issue when trying to make a request to an HTTP URL from another domain using AJAX. Every time I attempt this, I receive an error callback. DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load { ...

The sorting of objects by Lodash is not accurate

My aim is to arrange objects based on a specific property (price). var arr = [{ name: 'Apple', price: '1.03' }, { name: 'Cherry', price: '0.33' }, { name: &apo ...

Divide a string into separate array items where a specific character is found

Within my sentence are several characters (~). I want to split the text before each ~ into an array item, and then add a <br /> tag at the end of each item. I attempted using the replace method but it only worked for the first ~ and disregarded the ...