Node.js Mongoose.js string to ObjectId function Node.js Mongoose.js string to ObjectId function mongoose mongoose

Node.js Mongoose.js string to ObjectId function


You can do it like so:

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


You can do it like this:

var mongoose = require('mongoose');var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString


You can use this also

const { ObjectId } = require('mongodb');const _id = ObjectId("4eb6e7e7e9b7f4194e000001");

it's simplest way to do it