Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

node.js - mongoose: findOne using mongo _id

I get that this can be a duplicated question. I looked up at least 10 related questions and answers, but I am still not able to find the document.

I am trying to get the document using .findOne(). I have the _id that created by MongoDB. But, I get null for every search I try.

await mongoose.connection.db
                    .collection('testing')
                    .findOne({ _id: req.body.test_id }, (err, result) => {
                        if (err) {
                            res.status(400);
                        } else {
                            console.log(`whaaaaaahsidufh ${result}`);
                        }
                    });

I tried _id: mongoose.Type.ObjectId(req.body.test_id) and other possible way to search. How can I retrieve the result by using _id on mongoose?

question from:https://stackoverflow.com/questions/65602891/mongoose-findone-using-mongo-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use findById();

try {   

 const test = await mongoose.connection.db.collection('testing').findById(req.body.test_id);
    if (test ) {
        console.log(`whaaaaaahsidufh ${test}`);
    } else {
        console.log(`test not found`);
    }
}catch(err){
    res.status(400);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...