3

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

1
  • if you pass the string as the value to search on, does it work? I query using a string, e.g. const devices = await Device.find({ owner: req.user._id });. I think mongoDB handles any conversion to an ObjectId Commented Feb 12, 2020 at 23:05

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following:

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

Comments

0

Try this

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.