I'm using Node.js with MongoDB and TypeScript.
The following two lines of code:
const ObjectID = require("mongodb").ObjectID;
const id = new ObjectID("5b681f5b61020f2d8ad4768d");
compile without error.
But when I change the second line to:
const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");
I get an error:
Cannot find name 'ObjectID'
Why isn't ObjectID
recognised as a type in TypeScript?
Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.
To determine if a string is a MongoDB ObjectID, we can use the mongoose. isValidObjectId method.
An ObjectId in MongoDB is a 12-byte BSON type. In the 12-byte structure, the first 4 bytes of the ObjectId represent the time in seconds since the UNIX epoch. The next 3 bytes of the ObjectId represent the machine identifier. The next 2 bytes of the ObjectId represent the process ID.
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.
yarn add @types/mongodb
import {ObjectID} from 'mongodb';
That's enough to use ObjectID as type nowadays.
Even with types installed typescript will not correctly type require("mongodb").ObjectId
. You need to use require
as part of an import :
import mongodb = require("mongodb");
const ObjectID = mongodb.ObjectID;
const id: mongodb.ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");
If you want to stick to your original version, you have to realize you are not importing the type, you are just importing the constructor. Sometimes types and values have the same name and are imported together giving the illusion that are the same thing, but really types and values live in different universes. You can declare the associated type and get it from the module type:
const ObjectID = require("mongodb").ObjectID;
type ObjectID= typeof import("mongodb").ObjectID;
const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With