Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah")
.

- 3,074
- 3
- 19
- 17
11 Answers
You can do it like so:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

- 25,430
- 7
- 43
- 47
-
Yeah that's a bit cleaner in this case. May only need to use the mongo.BSONPure if doing fromTime() – talentedmrjones Feb 02 '12 at 17:56
-
4Does this throw an error if it's an invalid string? Looking for the best way to do input validation in a REST API for mongo id fields. – Zambonilli Jul 21 '14 at 18:42
-
1Doesn't really answer the question because using this methodology the string will be converted and not be the same as the original. – ed209 May 19 '15 at 13:22
-
mongoose.Types.ObjectId(id) but my id is undefined then what it will return ? new id or error – Keval Bhatt Dec 17 '15 at 09:14
-
3@KevinDente I'm using Nodejs with Typescript, i've tried your solution but still getting a string and my query does not return what it should return. any idea on how to do it on typescript ? – SOufiane Fadil Aug 11 '18 at 22:56
-
Need to add, the string you pass must follow mongoose conventions, otherwise you'll get this error: `Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters`. In other words, you CAN'T do this: `var mongo_id = mongoose.Types.ObjectId('blah')` – Alec Mather May 06 '20 at 23:55
-
What happens if I do ```var id = new mongoose.Types.ObjectId('4edd40c86762e0fb12000003');``` (added ```new```) ? seems to work the same... but why? – Shani Kehati Jun 16 '21 at 12:25
-
6Seems to work with common js require but using es6 `import mongoose from 'mongoose';` doesn't seem to work. `Argument of type 'import("mongoose").Types.ObjectId' is not assignable to parameter of type 'import("mongoose").Schema.Types.ObjectId'.`. Anybody else gettting this? – Stretch0 Jul 10 '21 at 09:18
-
Doesnt this generate a new ObjectId and not actually turn a string into a ObjectId? – Nikola-Milovic Aug 16 '21 at 12:49
-
2Seconding @Stretch0. Does not work with es6 and typescript. – Adam D Jan 04 '22 at 13:36
-
Does this work? var id = new mongoose.Types.ObjectId('4edd40c86762e0fb12000003'); – ShadowGames Nov 22 '22 at 14:03
-
Hello, to avoid the error when using import mongoose from mongoose, You can try with const id = new mongoose.Types.ObjectId('4edd40c86762e0fb12000003'), because seems to be a Class not a method – Martin Muñoz Dec 12 '22 at 14:43
-
@MartinMuñoz I am facing the same problem. I have tried ```const id = new mangoose.Types.ObjectId("string")``` but my problem is-- it populates an ObjectId with a *new* keyword in front. Is there any way to remove the *new* keyword from the result? – Fahad May 25 '23 at 14:28
-
I dont understand what you wanna do. The fix that I described is for compatibility issues between ES6 and CommonJS (basically it uses different ways of importing modules and syntax). Please provide some code and more detailed explanation of that you wanna achieve – Martin Muñoz May 29 '23 at 15:36
You can use this also
const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");
it's simplest way to do it

- 299
- 3
- 12
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

- 13,008
- 21
- 97
- 158

- 7,511
- 1
- 26
- 26
-
2Well, even more "new" standard is seems to be mongoose.mongo.BSONPure.ObjectID.createFromHexString() (as of mongoose 3.9.7) – Evereq Jan 16 '15 at 08:01
-
1For those who are attempting to do this, this is a much better answer than the selected answer because it will not transform the id if you are already using a mongo id. – ed209 May 19 '15 at 13:34
-
2
-
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid

- 13,008
- 21
- 97
- 158
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");

- 11,809
- 12
- 78
- 98
-
4Could you comment on the difference between `mongoose.Types.ObjectId` and `mongoose.mongo.ObjectId`? The object properties of mongoose are different, but they may be referencing the same method underneath. Please comment on the underlying methods on `Types` vs `mongo`. – steampowered Jun 20 '16 at 19:46
I couldn't resolve this method (admittedly I didn't search for long)
mongoose.mongo.BSONPure.ObjectID.fromHexString
If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.
You could use something like this however, which gives a bit more flex:
function toObjectId(ids) {
if (ids.constructor === Array) {
return ids.map(mongoose.Types.ObjectId);
}
return mongoose.Types.ObjectId(ids);
}

- 924
- 9
- 20
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
....
exports.AddSomething = (req,res,next) =>{
const newSomething = new SomeEntity({
_id:new mongoose.Types.ObjectId(), //its very own ID
somethingName:req.body.somethingName,
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID
})
}
...
Hope it Helps

- 463
- 5
- 6
If you want to use schema
const yourSchemma = new Schema({
"customerId": {
type: mongoose.Types.ObjectId,
required: true
}
});

- 184
- 3
- 4
For new versions, adding 'new' keyword to the selected answer worked, like this
var mongoose = require("mongoose");
var _id = new mongoose.Types.ObjectId("64b0ee2c189286a5abc6b4ba");

- 2,758
- 5
- 23
- 41
If you want to use ObjectId a lot and don`t want to use mongoose.types.ObjectId, you can destructure your declaration:
const {
Types: { ObjectId: ObjectId },
} = require("mongoose");
const id=ObjectId("4edd40c86762e0fb12000003")

- 91
- 1
- 6
You can do it like this:
import mongoose from "mongoose";
const { ObjectId } = mongoose.Types;
const id = ObjectId('4edd40c86762e0fb12000003');

- 363
- 3
- 10