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

3 answers

  • answered 2020-02-12 23:05 dk-na

    Try the following:

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

  • answered 2020-02-13 04:32 Nikhil Savaliya

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

  • answered 2020-02-13 04:37 Deepak Preman

    Try this

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