简体   繁体   中英

MongoDB findOne funtion returns null when comparing with id

I am using the following code to get the details of a user when I pass their id as a parameter:

   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value. My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

req.params.id comes as a string while your _id is an ObjectId so this won't work since MongoDB requires type equality first, you need to cast the value:

const itemId = mongoose.Types.ObjectId(req.params.id);

MongoDB wouldn't consider the "itemId" as a MongoDB id, therefore you need to transform it as shown below:

new mongodb.ObjectId(itemId)

This implies that:

const mongodb = require('mongodb')

As others already said, MongoDB expects _id to be an ObjectID. But if you are searching for ONE item, instead of using findOne use findById , which accepts id as a string.

const { Model } = require('./models'); // Model is your Mongoose Schema

server.get("/users/:id", async (req, res) => {
   const { id } = req.params;

   // This is the same as Model.findOne({ _id: new ObjectId(id) });
   const item = await Model.findById(id);

   return res.json(item);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM