Home > Software engineering >  Mongoose, get string record ID
Mongoose, get string record ID

Time:03-15

I am trying to setup a database using Mongoose for MongoDB, using nodejs. Currently when it performs findByID, it returns an object that I cannot seem to parse or turn into a string. I am trying to compare a supplied user id with the returned value as shown below. How can I perform a FindBy.. function and have the result in a string format, so I can perform comparisons? Thanks

        globalTest = doc._id;
        
        //const foundUser = Auth.findById(mongoose.Types.ObjectId(doc._id));
        const foundUser = Auth.findById(mongoose.Types.ObjectId(globalTest));//.lean().exec();
    
        if(globalTest===foundUser){
            console.log('match');
        }else{
            console.log('no match');console.log(foundUser ' vs ' globalTest);              
        }
        console.log('BREAK: ' foundUser._id);//always undefined

And the console output:

Saving: 622f6ed69f5b04b4c82fce74 no match
auth.findOne({ _id: new ObjectId("622f6ed69f5b04b4c82fce74") }) vs 622f6ed69f5b04b4c82fce74
BREAK: undefined

CodePudding user response:

As per your console output foundUser is returning the query, you need to execute it in order the query to run and get the data.

I'm assuming you are using async/await

const foundUser = await Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec();

if (globalTest == foundUser._id) {
    console.log('match');
} else {
    console.log('no match')
}

Callback Version

Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec((err, doc) => {
    if(err) console.error(err);

    if (globalTest == doc._id) {
        console.log('match');
    } else {
        console.log('no match')
    }

});
  • Related