2
votes

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

3
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 ObjectIddikuw

3 Answers

1
votes

Try the following:

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

Try this

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

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