How to set object ID as a data type in Node.js Mongoose?

Sometimes, we want to set object ID as a data type in Node.js Mongoose.

In this article, we’ll look at how to set object ID as a data type in Node.js Mongoose.

How to set object ID as a data type in Node.js Mongoose?

To set object ID as a data type in Node.js Mongoose, we can use Schema.ObjectId as the type.

For instance, we write

const mongoose = require('mongoose');
const {
  Schema
} = mongoose;
const {
  ObjectId
} = Schema;

const SchemaProduct = new Schema({
  categoryId: ObjectId,
  title: String,
  price: Number
});

to use the Schema constructor to create a new schema.

And we set the categoryId field to the ObjectId type by setting categoryId to ObjectId.

Conclusion

To set object ID as a data type in Node.js Mongoose, we can use Schema.ObjectId as the type.