Reputation: 1702
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.
Upvotes: 3
Views: 12834
Reputation: 1098
for me "_id.$oid"
didn't work. I had to use "_id"
as shown in following code snippet.
const { ObjectId } = require('mongodb');
...
collection.findOne({ "_id": ObjectId(req.params['id']) })
.then(...)
Upvotes: 0
Reputation: 1051
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?
Upvotes: 7