Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38183

How can I generate an ObjectId with mongoose?

I'd like to generate a MongoDB ObjectId with Mongoose. Is there a way to access the ObjectId constructor from Mongoose?

Upvotes: 224

Views: 236629

Answers (7)

Mangesh Joshi
Mangesh Joshi

Reputation: 56

const mongoose = require('mongoose');
const objectId = new mongoose.Types.ObjectId();

console.log(objectId);

Upvotes: 0

Mechanic
Mechanic

Reputation: 5380

The code that worked for me in mongoose v8 (+ typescript) was this:

const id = new mongoose.Types.ObjectId().toString()

Upvotes: 0

Canonne Gregory
Canonne Gregory

Reputation: 424

The import is mongo from mongoose, the node-mongodb-native driver. If you open the package you can verify !

import { mongo } from 'mongoose'
const newId = new mongo.ObjectId()

Upvotes: 1

Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38183

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.


Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:

var id = new mongoose.Types.ObjectId();

You can read more about the Types object at Mongoose#Types documentation.

Upvotes: 445

MattCochrane
MattCochrane

Reputation: 3090

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

Upvotes: 29

Poyoman
Poyoman

Reputation: 1966

I needed to generate mongodb ids on client side.

After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.

If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :

const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2

Note: There is also an npm project named bson-objectid being even lighter

Upvotes: 34

steampowered
steampowered

Reputation: 12062

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

Upvotes: 70

Related Questions