Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my MongoDB ObjectID recognised as a type in TypeScript?

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?

like image 616
Mary Avatar asked Dec 30 '18 01:12

Mary


People also ask

What is the type of ObjectId in MongoDB?

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.

Can I determine if a string is a MongoDB ObjectId?

To determine if a string is a MongoDB ObjectID, we can use the mongoose. isValidObjectId method.

How an ObjectId type is composed in MongoDB?

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.

What is the use of ObjectId in MongoDB?

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.


2 Answers

  1. yarn add @types/mongodb
  2. use import import {ObjectID} from 'mongodb';

That's enough to use ObjectID as type nowadays.

like image 137
Stanislav Avatar answered Sep 22 '22 14:09

Stanislav


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");
like image 26
Titian Cernicova-Dragomir Avatar answered Sep 20 '22 14:09

Titian Cernicova-Dragomir