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.
Source : https://futurestud.io/tutorials/mongodb-how-to-create-an-objectid-from-a-string-in-node-js
No comments:
Post a Comment