Express MongoDB find() based on _id field

偶尔善良 提交于 2019-12-11 02:19:01

问题


So In my express app, I am trying to find() based on my _id field.

See my MongoDB record below.

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

When I use .find( _id: id ), my id param = 58c2a5bdf36d281631b3714a.

How would I convert / use this to get my MongoDB record?

Here is my Express call:

//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);
        });

});

Any help or advice is appreciated. Thank you in advance.

EDIT: (my revised query)

//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)
    });

});

article is Currently returning NULL.


回答1:


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

or even more specific:

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

EDIT:
Converting string into ObjectId type before querying

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

Reference: If i have a mongo document id as a string how do I query for it as an _id?



来源:https://stackoverflow.com/questions/42790527/express-mongodb-find-based-on-id-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!