基于_id字段的Express MongoDB find()

3

在我的express应用程序中,我正在尝试基于我的_id字段进行查找(find())。

请看下面的MongoDB记录。

{
        "_id": {
            "$oid": "58c2a5bdf36d281631b3714a"
        },
        "title": "EntertheBadJah",
        "subTitle": "Lorem ipsum dolor",
        "thmbNailImg": "",
        "headerImg": "",
         ... BLAH BLAH BLAH

当我使用 .find( _id: id ) 时,我的 id 参数为 58c2a5bdf36d281631b3714a
我该如何将其转换/使用以获取我的 MongoDB 记录?
以下是我的 Express 调用:
//GET ARTICLE
app.get('/api/article', (req, res) => {

    var id = req.query.id
    var article = [];

    db.collection('articles')
        .find( _id: id )
        .then(result => {
            article = articles.concat(result);
        }).then(() => {
            res.send(article);
        }).catch(e => {
            console.error(e);
        });

});

任何帮助或建议都将不胜感激。提前谢谢。

编辑:(我修订后的问题)
//GET ARTICLE
app.get('/api/article', (req, res) => {

    var id = req.query.id

    db.collection('articles').findOne({
        "_id.$oid": id
    }, function(err, article) {
        res.send(article);
        console.log(article)
    });

});
目前返回为NULL。

1
尝试使用以下代码:db.collection('articles').find( {"_id.$oid": id })。更多信息请参考:https://docs.mongodb.com/v3.2/core/document/#embedded-documents - ajai Jothi
@danjonescidtrix 当你说“_58c2a5bdf36d281631b3714a作为整数_”时,这是正确的吗 - 是整数吗?那应该是字符串吗? - Vince Bowdren
这是一个整数,我的查询中应该是字符串吗?@VinceBowdren - daniel aagentah
它是什么整数?"58c2a5bdf36d281631b3714a" 看起来像一个字符串。 - Vince Bowdren
1
你需要将字符串 "58c2a5bdf36d281631b3714a" 转换为 ObjectId。我完全不了解 Express 环境,但这可能只需要简单的 ObjectId(req.query.id) - Vince Bowdren
显示剩余9条评论
2个回答

7
db.collection('articles')
    .find( {"_id.$oid": id} )
    .

或者更具体地说:

db.collection('articles')
    .findOne( {"_id.$oid": id} )
    .

编辑:
在进行查询之前将字符串转换为ObjectId类型

var ObjectID = require('mongodb').ObjectID;   
db.collection('articles')
    .findOne( {"_id.$oid": new ObjectID(id)})
    .

参考:如果我有一个作为字符串的mongo文档id,如何将其查询为_id?


这个问题很容易被混淆。如果您已经有了一个MongoDB文档ID作为字符串,那么您可以将它直接用作查询条件,而无需将其转换为ObjectId类型。例如:

db.collection.find({ "_id": "your-document-id-as-a-string" })

这将返回与提供的ID匹配的文档。


0
对我来说,"_id.$oid" 不起作用。我不得不使用以下代码片段中显示的 "_id"
const { ObjectId } = require('mongodb');

...
collection.findOne({ "_id": ObjectId(req.params['id']) })
  .then(...)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接