I am hitting http://localhost:4000/api/getsinglepost/6199ae17a515fca1c132c901
This code give me empty array []
.
When i removed $match give me all posts with "comment_section": []
I am uploading post and comment table screenshots as well as the response i need .
exports.singlePost = async (req, res) => {
const getit = await postTable.aggregate([
{
$match: { _id: req.params.id }
},
{
$lookup:
{
from: "commenttables",
localField: "_id",
foreignField: "postID",
as: "comment_section"
}
}
])
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "something wrong while getting details"
});
});
};
My post table:-
My comment table:-
Response i need like:-
MongoDB query operators are type-sensitive. req.param.id
most likely contains a string, while the _id
fields contain ObjectId
, so they don't match.
You can convert the string to ObjectId using the bson module that comes with the mongodb node.js driver.
After requiring the driver
const mongo = require("mongodb")
Convert with:
mongo.ObjectId(req.param.id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.