Qiulang
Qiulang

Reputation: 12395

What is the difference between mongo ObjectID, ObjectId & Mongoose ObjectId

I can't figure out the difference between mongo ObjectID & ObjectId. The document said ObjectId, but when I read the code, I see

import { ObjectID } from 'bson';

To make things even more confused is the mongoose document & code. The mongoose also says ObjectId http://mongoosejs.com/docs/api.html#types-objectid-js. But when I read the codes I saw

// mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is
//   commonly used in mongoose and is found in an example in the docs:
//   http://mongoosejs.com/docs/api.html#aggregate_Aggregate
// constructor exposes static methods of mongodb.ObjectID and ObjectId(id)
type ObjectIdConstructor = typeof mongodb.ObjectID & {
  (s?: string | number): mongodb.ObjectID;
}

So what exactly is the difference between ObjectID, ObjectId and mongoose ObjectId?

I found there was another SO talking about this BSON::ObjectId vs Mongo::ObjectID

The links there were dead though and it didn't take about mongoose. So I hope my question won't be marked as duplicated.

Upvotes: 14

Views: 4252

Answers (2)

NARGIS PARWEEN
NARGIS PARWEEN

Reputation: 1596

  1. ObjectID: This is the BSON ObjectID datatype that MongoDB uses. It's a 12-byte identifier typically made up of a timestamp, machine identifier, process id, and a counter. This is provided by the native MongoDB driver for Node.js.

  2. ObjectId: This is often seen in the MongoDB shell and it is essentially the same as ObjectID. It's just a different naming convention. When you're working in the MongoDB shell, you'll use ObjectId. But in a Node.js environment using the MongoDB native driver, you'll use ObjectID.

  3. Mongoose ObjectId: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose provides a straight-forward, schema-based solution to model your application data with MongoDB. The ObjectId in Mongoose is essentially the same as ObjectID in the MongoDB native driver for Node.js. Mongoose just provides an extra layer of convenience and added functionality.

In summary, these three terms are essentially referring to the same thing but are used in slightly different contexts (MongoDB shell vs. Node.js environment vs. Mongoose environment).

Upvotes: 0

Akash Kukkar
Akash Kukkar

Reputation: 99

Mongo ObjectID is a unique 12-byte identifier which can be generated by MongoDB as the primary key.

An ObjectID is a unique, not null integer field used to uniquely identify rows in tables

In Mongoose ObjectID is same as Mongo ObjectID and referencing an object in another collection

Upvotes: 0

Related Questions