Mongoose is the most widely used MongoDB ODM for Node.js. By default, Mongoose uses MongoDB’s ObjectId as the _id field. UUID v7 is a compelling replacement: it provides millisecond-precision time ordering (vs ObjectId’s second-level), is a standard format usable across languages, and avoids vendor lock-in to MongoDB’s ObjectId format. See UUID in MongoDB for the broader MongoDB context.

Schema with UUID v7 _id

import mongoose, { Schema, Document } from 'mongoose';
import { v7 as uuidv7 } from 'uuid';

interface IOrder extends Document {
  _id: string;
  customerId: string;
  total: number;
  status: string;
}

const orderSchema = new Schema<IOrder>(
  {
    _id: {
      type: String,
      default: () => uuidv7(),  // UUID v7 generated at document creation
    },
    customerId: { type: String, required: true },
    total: { type: Number, required: true },
    status: { type: String, default: 'pending' },
  },
  {
    timestamps: false,  // UUID v7 _id encodes creation time — createdAt is redundant
  }
);

export const Order = mongoose.model<IOrder>('Order', orderSchema);

Creating and querying documents

// Create — UUID v7 generated by default()
const order = await Order.create({
  customerId: 'user-abc',
  total: 99.99,
});
console.log(order._id); // 018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f

// Find by UUID v7 _id
const found = await Order.findById('018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f');

// Sort by _id = sort by creation time (UUID v7 lexicographic = chronological)
const recentOrders = await Order.find({}).sort({ _id: 1 }).limit(20);

Cursor pagination with UUID v7

async function listOrders(cursor?: string, limit = 20) {
  const query = cursor
    ? Order.find({ _id: { $gt: cursor } })
    : Order.find({});

  const orders = await query
    .sort({ _id: 1 })
    .limit(limit)
    .lean();

  const nextCursor = orders.length === limit
    ? orders[orders.length - 1]._id
    : null;

  return { orders, nextCursor };
}

UUID v7 string comparison ($gt) is lexicographic, which matches chronological order for UUID v7. See UUID v7 for Cursor Pagination.

Pre-save hook for validation

orderSchema.pre('save', function (next) {
  if (this.isNew && !this._id) {
    this._id = uuidv7();
  }
  // Optional: validate UUID v7 version
  if (this._id.charAt(14) !== '7') {
    return next(new Error(`_id must be UUID v7, got version ${this._id.charAt(14)}`));
  }
  next();
});

Query helper: find documents created after a timestamp

orderSchema.query.createdAfter = function (date: Date) {
  // Build UUID v7 lower bound from timestamp
  const ms = date.getTime();
  const prefix = ms.toString(16).padStart(12, '0');
  const lowerBound = `${prefix.slice(0,8)}-${prefix.slice(8,12)}-7000-8000-000000000000`;
  return this.where({ _id: { $gte: lowerBound } });
};

// Usage
const todaysOrders = await Order.find({}).createdAfter(new Date('2026-10-17'));

Indexes on UUID v7 _id

MongoDB automatically creates an index on _id. For UUID v7, the string index is efficient for:

No secondary createdAt index is needed for time-ordered queries — sort({ _id: 1 }) achieves the same result. See UUID in MongoDB.

Further reading

External references

Frequently asked questions

How do I use UUID v7 as _id in a Mongoose schema?

Set _id: { type: String, default: () => uuidv7() } in your schema definition and { _id: false } is not needed — you are overriding, not disabling. Mongoose will use the string UUID v7 as the document's _id. All MongoDB collection indexes and queries work with string _id values. See UUID in MongoDB.

Should I store UUID v7 as a string or Binary in MongoDB?

String storage (36 chars) is simpler and human-readable. Binary SUBTYPE_UUID (16 bytes) is 2.25× more compact and sorts correctly in MongoDB's byte-order comparison. For most Mongoose applications, string storage is the correct choice — the simplicity outweighs the storage saving. See UUID in the MongoDB Driver for the Binary pattern.

Does UUID v7 replace ObjectId's time-sortability in MongoDB?

Yes. MongoDB's ObjectId encodes a 4-byte Unix second timestamp as its prefix — giving roughly 1-second resolution for insertion order. UUID v7 encodes a 48-bit Unix millisecond timestamp — providing millisecond-precision time ordering, which is significantly better than ObjectId's second-level granularity.