How to create an id using mongoose in Javascript?

In this tutorial, we will learn to create an id using mongoose in JavaScript. Users can use the Mongoose NPM package in NodeJS to use MongoDB with NodeJS or connect MongoDB with the application.

While storing the data in the MongoDB database, we must add a unique id to every data collection. However, if we don't add an id, it generates automatically and adds to the data.

Syntax

Users can follow the syntax below to create an id using mongoose in JavaScript.

var newId = new mongoose.mongo.ObjectId();

In the above syntax, we access the 'mongo' from the mongoose and invoke the 'ObjectId()' method to generate a new id.

Alternative Methods

There are multiple ways to create ObjectIds in Mongoose:

// Method 1: Using mongoose.mongo.ObjectId()
var newId1 = new mongoose.mongo.ObjectId();

// Method 2: Using mongoose.Types.ObjectId()
var newId2 = new mongoose.Types.ObjectId();

// Method 3: Using ObjectId constructor from mongodb
const { ObjectId } = require('mongodb');
var newId3 = new ObjectId();

Example 1: Auto-Generated ObjectId

In the example below, we have connected MongoDB with NodeJS. We created the mongoose schema and model. The data object contains the data to save into the MongoDB database. We use the save() method to save a collection of data into MongoDB.

We haven't assigned any id to the data, so it has automatically generated it.

const mongoose = require("mongoose");

// Database connection
mongoose
  .connect(
    "mongodb+srv://shubhamvora05:Stockdata@stockdata.lrlgm.mongodb.net/StockList?retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => {
    console.log("Connected to database");
  })
  .catch((err) => {
    console.log("Error connecting to DB", err.message);
  });

const dataSchema = new mongoose.Schema({
  name: String,
  type: String,
});

const dataModel = mongoose.model("dataModel", dataSchema);

const data = {
  name: "Delhi",
  type: "city",
};

var dataDetails = new dataModel(data);
dataDetails
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Output

$ node index.js
Connected to database
{
  name: 'Delhi',
  type: 'city',
  _id: new ObjectId("642b937407844923e4fddee7"),
  __v: 0
}

Example 2: Custom ObjectId Generation

In the example below, we use the 'mongo.ObjectId()' method to generate an id for the data. After that, we printed the generated id in the console. Next, we save the data by assigning the newly generated id.

In the output, users can observe that the id of the data is the same as the id generated by us.

const mongoose = require("mongoose");

// Database connection
mongoose
  .connect(
    "mongodb+srv://shubhamvora05:Stockdata@stockdata.lrlgm.mongodb.net/StockList?retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => {
    console.log("Connected to database");
  })
  .catch((err) => {
    console.log("Error connecting to DB", err.message);
  });

const dataSchema = new mongoose.Schema({
  name: String,
  type: String,
});

const dataModel = mongoose.model("dataModel", dataSchema);
var newId = new mongoose.mongo.ObjectId();
console.log(newId);

const data = {
  _id: newId,
  name: "Gujarat",
  type: "state",
};

var dataDetails = new dataModel(data);
dataDetails
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Output

$ node index.js
new ObjectId("642b9796987428b8b945f477")
Connected to database
{
  name: 'Gujarat',
  type: 'state',
  _id: new ObjectId("642b9796987428b8b945f477"),
  __v: 0
}

Example 3: ObjectId with Custom String

In the example below, we have passed the string of 12 bytes as a parameter of the ObjectId() method. It generates the new id according to the value passed as a parameter. However, users can also pass the 24 hex characters as a parameter.

In the output, users can observe the id of 24 hex characters.

const mongoose = require("mongoose");

// Database connection
mongoose
  .connect(
    "mongodb+srv://shubhamvora05:Stockdata@stockdata.lrlgm.mongodb.net/StockList?retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => {
    console.log("Connected to database");
  })
  .catch((err) => {
    console.log("Error connecting to DB", err.message);
  });

const dataSchema = new mongoose.Schema({
  name: String,
  type: String,
});

const dataModel = mongoose.model("dataModel", dataSchema);
var newId = new mongoose.mongo.ObjectId('234556567123');

const data = {
  _id: newId,
  name: "Lokesh",
  type: "name",
};

var dataDetails = new dataModel(data);
dataDetails
  .save()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Output

$ node index.js
Connected to database
{
  name: 'Lokesh',
  type: 'name',
  _id: new ObjectId("323334353536353637313233"),
  __v: 0
}

ObjectId Structure

MongoDB ObjectIds are 12-byte identifiers consisting of:

  • 4 bytes representing timestamp (seconds since Unix epoch)
  • 5 bytes of random value unique to machine and process
  • 3-byte incrementing counter (initialized randomly)

Common Use Cases

  • Pre-generating IDs: Create ObjectIds before saving documents
  • Reference relationships: Use ObjectIds to reference other documents
  • Batch operations: Generate multiple IDs for bulk insertions

Conclusion

Users learned to generate ObjectIds in MongoDB using Mongoose. The ObjectId() method can generate random IDs or create specific ones using 12-byte strings or 24 hex characters as parameters.

Updated on: 2026-03-15T23:19:01+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements