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.

Example 1

In the example below, we have connected MongoDB with NodeJS. However, users need to change their account details. After that, we created the mongoose schema. Using the schema, we have created the mongoose model.

The data object contains the data to save into the MongoDB database. After that, we use the save() method to save a collection of data into MongoDB. If it stores data successfully, it prints the result. In the output, users can observe the id of the data.

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

On execution, it will produce the following output −

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

Example 2

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

On execution, it will produce the following output −

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

Example 3

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

On execution, it will produce the following output −

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

Conclusion

Users learned to generate a random id in the MongoDb. Also, users learned to generate a specific id for the MongoDB data by passing the 12 bytes of string or 24 hex characters as a parameter of the ObjectId() method.

Updated on: 19-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements