问题
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