I have two collections in my MongoDB that I'd like to join with an aggregate query, but am having difficulty returning the resultant object(s) to the console. It currently returns nothing, which, in itself, is strange. Hoping you can help...
Collection 1 is scrapedData & scrapes articles from the Chicago Tribune:
{
"_id": ObjectId("123"),
"headline":"Cubs Javier Baez Wins Silver Slugger Award",
"link": "www.chicagotribune.com",
}
Collection 2 is called comments and includes comments posted to my site linked to each article found from the scrape:
{
"_id": ObjectId("456"),
"articleId":"123",
"author": "John Chicago"
"message": "Good for Javier!"
}
{
"_id": ObjectId("789"),
"articleId":"123",
"author": "Jane Q."
"message": "MVP! MVP!"
}
My current attempt at pulling together a response from the database that joins article headline, and all comments related to it, is:
db.comments.aggregate([
{$match : {articleId : JSON.stringify(123)}},
{
$lookup:
{
from: "scrapedData",
localField: "articleId",
foreignField: "_id",
as: "commentsPosted"
}
}
]),function(err, response) {
if(err) {
console.log(err);
} else {
console.log(response);
}
}});
Any pointers you can share will be greatly appreciated.
As per the aggregate documentation your callback function and overall JS is somewhat messed up, try this:
db.comments.aggregate([
{ $match: { articleId: JSON.stringify(123) } },
{ $lookup: {
from: "scrapedData",
localField: "articleId",
foreignField: "_id",
as: "commentsPosted"
}}], function(err, response) {
if (err) {
console.log(err);
} else {
console.log(response);
}});
Or better using Promises
:
return db.comments.aggregate([
{ $match: { articleId: JSON.stringify(123)}},
{ $lookup: {
from: "scrapedData",
localField: "articleId",
foreignField: "_id",
as: "commentsPosted"
}}])
.exec()
.then(function(response) {
console.log(response)
}).catch(function(e){
console.log(e)
})