MongoDB — How to Create an ObjectId from a String in Node.js

MongoDB requires each document to contain an _id field. If the _id field is not present when inserting a document, MongoDB generates an ObjectId for you.

You can use ObjectIds as the primary key in your application. When requesting information from the browser you may send an ObjectId as an identifier for a given resource. As with any value in URLs, ObjectIds are represented as a string. You need to convert the request parameters in your route handler.

This tutorial shows you how to create an ObjectId instance from a string value.

MongoDB Series Overview

Create a MongoDB ObjectId from a String

You can translate a MongoDB ObjectId from a string to an ObjectId instance using the ObjectId class exported from the MongoDB Node.js driver. Pass your string value as an argument to the constructor and the package creates the 12-byte ObjectId instance:

import { ObjectId } from 'mongodb'

const objectId = new ObjectId('your-object-id-as-string')  

Please notice: the ObjectId constructor validates your input and throws an error if the provided string value is not a valid hex representation of an ObjectId. The hex format is the one you know from MongoDB, like 61dc2d31bbe643fc32022a5f.

Be prepared to catch the related MongoDB error when users try to challenge your backend with non-ObjectId string values.


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.