猫鼬:findOne 使用 mongo _id

时间:2021-01-06 20:22:20

标签: node.js mongodb mongoose

我知道这可能是一个重复的问题。我查了至少 10 个相关问题和答案,但仍然找不到文档。

我正在尝试使用 .findOne() 获取文档。我有 MongoDB 创建的 _id。但是,我尝试的每次搜索都为空。

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

我尝试了 _id: mongoose.Type.ObjectId(req.body.test_id) 和其他可能的搜索方式。如何通过在 mongoose 上使用 _id 来检索结果?

1 个答案:

答案 0 :(得分:1)

你可以使用 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);
}