MongoDB Join/Aggregate 查询在控制台中返回静默

MongoDB Join/Aggregate Query Returning Silence in Console

我的 MongoDB 中有两个 collections,我想加入聚合查询,但很难将结果 object(s) 返回到控制台.目前 returns 什么都没有,这本身就很奇怪。希望你能帮忙...

Collection 1 是 scrapedData & 从芝加哥论坛报抓取文章:

{
"_id": ObjectId("123"),
"headline":"Cubs Javier Baez Wins Silver Slugger Award",
"link": "www.chicagotribune.com",
 }

Collection 2 被称为 comments 并且包括发布到我的网站的评论链接到从抓取中找到的每篇文章:

  {
  "_id": ObjectId("456"),
  "articleId":"123",
  "author": "John Chicago"
  "message": "Good for Javier!"
  }
  {
  "_id": ObjectId("789"),
  "articleId":"123",
  "author": "Jane Q."
  "message": "MVP! MVP!"  
  }

我目前试图从数据库中收集一个加入文章标题的响应,以及与之相关的所有评论,是:

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

如果您能分享任何建议,我们将不胜感激。

根据 aggregate documentation 你的回调函数和整个 JS 有点乱,试试这个:

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

或者更好地使用 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)
 })