Easily switch to using String id instead of ObjectId when working with MongoDataSource in Apollo Server

We are currently working with a MongoDB database that uses string IDs instead of the typical 12 bytes or 24 hex format. These IDs were generated by MeteorJS.

As we develop a GraphQL layer using apollo server, we encountered an issue when trying to load data using apollo-datasource-mongodb and calling the findOneById method. The error message received was:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
    at new ObjectID (/app/node_modules/bson/lib/bson/objectid.js:59:11)
    at Function.ObjectID (/app/node_modules/bson/lib/bson/objectid.js:40:43)
    at file:///app/connectors/legacy.js:3:21
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)
/app/node_modules/bson/lib/bson/objectid.js:59

This error occurs because the module is attempting to transform our string ID into a MongoDB ObjectId, which is not compatible with our current ID format.

Upon reviewing the apollo-datasource-mongodb repository, it appears that it does have the capability to handle string IDs:

    findOneById(
      id: ObjectId | string,
      options?: Options
    ): Promise<TData | null | undefined>

Source: https://github.com/GraphQLGuide/apollo-datasource-mongodb/blob/master/index.d.ts

Our Users dataSource implementation:

import { MongoDataSource } from 'apollo-datasource-mongodb'

export class Users extends MongoDataSource {
}

The initiation in the context layer:

Users: new Users(legacy.collection('users'))

The call in the model layer:

async findOneById(obj, { id }, {dataSources: { Users }}) {
  return await Users.findOneById(id)
}

We do not utilize mongoose & typescript in our project.

If anyone has any ideas on how to resolve this issue and make it work, please share!

Answer №1

After some investigation, I discovered that the string ID is not compatible. For further information, please visit this link

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

Node.js implementation for routing WebSocket requests from an HTTPS server to an HTTP server

I'm currently developing a Node.js proxy server that handles routing requests from a website to a local endpoint. The website has the capability to run either on a local server or in a cloud instance, so the proxy needs to be able to support both HTTP ...

Steps to remove TLS 1.0 and 1.1 server-side support for my application running on AWS

Currently, I am tasked with improving a Node.js application. The existing code utilizes the http.createServer() method to set up a server. Since SSL configurations are managed at a level above the application code, the https object with certificate options ...

NPM continues to run smoothly in support of the Hastebin server operations

I have set up Hastebin at /var/www/paste/hastebin/ To initiate the NPM server, I need to navigate to the hastebin directory and then execute: npm start This command starts the server with the following output: # npm start > <a href="/cdn-cgi/l/e ...

What specific mongoose query encounters issues when implementing async await?

I have a small requirement. I need to insert data into 2 different collections, Test1_Model and Test2_Model, which are Mongoose Models in Node.js. try { const test1 = new Test1_Model({ name: "Dummy" }); const saveTest1 = await test1.save(); ...

Is it possible to incorporate a placeholder within npm scripts and then dynamically replace it using the npm command?

Looking to update a specific part of an npm script without creating multiple scripts. The current script is as follows: "scripts": { "test:chrome": "set DEV_MODE=staging& npx testcafe \"chrome --start-fullscreen\" automation_suite/tests" } ...

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

troubleshooting Laravel 6 authentication issue with npm run dev command

With the release of Laravel 6, a new method for implementing authentication has been introduced. To do this, you first need to install the laravel/ui package via composer by running composer require larvel/ui. Next, generate the scaffolding using the des ...

What is the process for creating and registering custom Handlebars functions?

Despite spending plenty of time searching, I am still unable to find detailed information on where exactly to place my custom handlebars helpers. Should they be added in a <script> tag within my webpage's .hbs file? Or should I include them in a ...

Updating a mongoose model with an array of objects: A step-by-step guide

Could you provide insight on how to modify the likes array using Mongoose? var postSchema = new mongoose.Schema({ author: String, content: String, date: String, likes: [{theID: String}], numDate: Number }); var UserSchema = mongoose.S ...

Best practices for Mocha testing: steer clear of using '../../' in your require statements

Looking at how my folders are structured, here's an example: /backend/services/service.js /test/backend/services/service.js In all the service tests, I find myself doing this: var service = require('../../../backend/services/service') Is ...

What steps do I need to take to set up Webstorm 10 so that it automatically runs npm install --force before

Is there a way to configure my debug settings in Webstorm so that I can automatically run "npm install --force" on a shared submodule before launching the application for debugging? This would save me time and ensure that everything is set up properly. I ...

Inform the user that an error has occurred when attempting to perform an invalid

While using redux promise middleware for my front end, I am wondering about the correct status code to throw from my backend in case of an error. I know that I can use res.status(500).json(something), but is 500 the appropriate code for all types of erro ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

Navigating the Promise Flow in NodeJS: Tips for Regulating Execution

I am trying to gain a better understanding of nodeJS by using the following code to execute CMD operations one by one. However, I have noticed that due to the event loop, it gets executed in random variations. Here is my code: const exec = require('c ...

Personalize the Loopback response following a successful save operation

I'm working on a Loopback 2.x application where I have models for Conversations and Messages, with a relationship of "Conversation has many messages." My goal is to receive a customized JSON response for the POST conversations/:id/messages endpoint, r ...

Is it possible to have various optional query parameters in Express?

In my Express application, I have a route that sends a GET request to the 'challenges' collection in MongoDB. This route is designed to find a specific challenge by its section number and challenge number. Here is the code snippet for this funct ...

Troubleshooting Email Communication Errors: A Persistent Challenge

I am new to nodemailer and trying to work on a simple application. However, I keep encountering errors within the nodemailer module when running my app. Here is my app.js code: const nodemailer = require('nodemailer'); const transporter = node ...

Encountering multiple npm warnings and issues in my React Native project resulting in app crashes

Having a bit of trouble with react-native addiction since yesterday................ https://i.stack.imgur.com/9QNsi.png It's causing issues with navigating to certain screens. Below is a snippet from my package.json: { "name": "test2", "version ...

node.js allows authorized users to access folders in an express application

I am currently working on a feature that will allow users to save and download static files, but I want these files to only be accessible to logged in (authorized) users. routes/files.js var express = require('express'); var router = express.Rou ...

What is the best way to retrieve the most up-to-date status for every identifier in the table?

Here is a table for reference: mysql> desc foo; +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+------------- ...