I was working on a Typescript web project that used MongoDB and ExpressJS. I used a MongoDB query to find and delete a document from MongoDB using the HTTP DELETE method. During the MongoDB query, I got mixed up with a term named new and ObjectID. Here are the code snippets:
//Without new Keyword
const resData: DeleteWriteOpResultObject = await data
.collection("posts")
.deleteOne({
_id: ObjectID(req.params.id),
});
//With new keyword
const resData: DeleteWriteOpResultObject = await data
.collection("posts")
.deleteOne({
_id: new ObjectID(req.params.id),
});
Both are working fine as I expected. But I want to know what's the difference between these two. Is there any memory-related difference or something else?
While googling I got an article also. I am attaching the link here.
CodePudding user response:
According to the official driver documentation, ObjectId
is a class which means you need to use new
to instantiate it.
However, looking at the actual implementation, it will allow itself to be called as a regular function, in which case it will return new ObjectId(...)
(so it will instantiate itself automatically).