cniblett
cniblett

Reputation: 43

Cannot convert string to ObjectId in NodeJS

I'm pulling my hair out.

I've tried using mongoose:

const ObjectId = require('mongoose').Types.ObjectId;

let id = new ObjectId(peson["_id"]);

When I console.log(id) it just shows the string value. When I append the id into an array in another object I'm using, and I JSON.stringify() that whole object I get just the '1djd892jowidj3wfejk93' string values.

When I pass my searchObject to Mongo, it doesn't return results.

I've also tried using the native MongoDB driver for node:

const {ObjectId} = require('mongodb');

let id = Objectid("1djd892jowidj3wfejk93")

this also returns just a string value when when logging to the console and also embedding in parent search request. JSON.stringify() shows just the string, and the query returns empty.

the native NodeJs mongoDb driver

Upvotes: 3

Views: 4981

Answers (4)

ha6755ad
ha6755ad

Reputation: 21

The correct way to do this as of December 2023 is as follows

import { ObjectId } from 'mongodb';

const id = ObjectId.createFromHexString(person._id);

If you explore the ObjectId class a bit you can see the other similar methods available. There's a solution in there for sure.

Upvotes: 2

Deepak Preman
Deepak Preman

Reputation: 113

Try this

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('1djd892jowidj3wfejk93');

Upvotes: 0

Nikhil Savaliya
Nikhil Savaliya

Reputation: 2166

You don't need to use extra dependency if you are using mongoose,

const mongoose = require('mongoose');

function convertToObjectID(id) {
    return mongoose.Types.ObjectId(id)
}

Upvotes: -1

dk-na
dk-na

Reputation: 141

Try the following:

const {ObjectID} = require('mongodb');
const id = new ObjectID('5e059042b091f6000a4bf236');

Upvotes: 1

Related Questions