259

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").

0

12 Answers 12

578

You can do it like so:

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

For new versions:

var id = new mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
Sign up to request clarification or add additional context in comments.

16 Comments

Does 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.
Doesn't really answer the question because using this methodology the string will be converted and not be the same as the original.
@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 ?
Seems 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?
Seconding @Stretch0. Does not work with es6 and typescript.
|
29

You can use this also

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

it's simplest way to do it

Comments

19

For new versions, adding 'new' keyword to the selected answer worked, like this

var mongoose = require("mongoose");
var _id = new mongoose.Types.ObjectId("64b0ee2c189286a5abc6b4ba");

1 Comment

For even newer version ObjectId is deprecated so you can use createFromHexString like so: import { Types } from 'mongoose'; const id = "123"; const result = Types.ObjectId.createFromHexString(id);
14

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

4 Comments

Well, even more "new" standard is seems to be mongoose.mongo.BSONPure.ObjectID.createFromHexString() (as of mongoose 3.9.7)
For 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.
This no longer works, use the accepted answer instead
BSONPure isn't a part of mongoose.mongo for me. Can anybody confirm?
9

Judging from the comments, you are looking for:

mongoose.mongo.BSONPure.ObjectID.isValid

Or

mongoose.Types.ObjectId.isValid

Comments

9
var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");

1 Comment

Could 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.
6

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);
}

Comments

4

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

Comments

3

You can do it like this:

import mongoose from "mongoose";

const { ObjectId } = mongoose.Types;

const id = ObjectId('4edd40c86762e0fb12000003');

Comments

1

If you want to use schema

const yourSchemma = new Schema({
"customerId": {
    type: mongoose.Types.ObjectId,
    required: true
}

});

Comments

0

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")

Comments

0

I am providing a chunk of code which is working. I am using mongoose( version ^7.4.0), typescript and node.js( version 16.16.0). I use Object
const sSchema = new Schema({ "Cell Phone": String, "Work Phone": String });

 const servicesModel = mongoose.model('Services', sSchema);

 const objectId = Object("63aed3cc10149ed38f1a24c0");
 servicesModel.find({ "_id" : objectId}).then(async (locationService) => {
 console.log(locationService);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.