Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to be able to obtain only the string that makes up the Id in a query to MongoDB

I’m using mongoDB, mongoose and typescript and I need to keep the document ids when I query but I can only get the type _id: new ObjectId("62aa4bddae588fb13e8df552") . I only need to keep the string "62aa4bddae588fb13e8df552" to later store it and do other processing. I can’t get rid of the new ObjectId

async findById(id:string) {
    const convert = {"_id":id}
    const userfindById = await userModel.findById(convert);
    const iD = userfindById?._id
    return userfindById;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ObjectId is just a type :

https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid

If you want to get the string you can extract with _id.toString(), if you want to store the string you should change the type of _id (or create a new property)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading