ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
To create a new objectID manually within the MongoDB you can declare objectId as a method. In simple words, we can say that object ID is a unique identifier for each record. In the below image you can observe that we are declaring a variable having object ID method as a value and it will return unique hexadecimal.
To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
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.
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();
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
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With