MongoDB在控制台中加入/聚合查询返回沉默

时间:2018-11-17 22:57:35

标签: mongodb mongodb-query mongojs

我的MongoDB中有两个集合,我想通过聚合查询进行联接,但是很难将结果对象返回到控制台。它当前不返回任何东西,这本身就是奇怪的。希望您能提供帮助...

集合1是 scrapedData 并从Chicago Tribune中刮取文章:

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

收藏集2称为评论,其中包含张贴到我的网站的评论,这些评论与从刮板上找到的每篇文章相关联:

  {
  "_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);
        }
      }}); 

任何可以共享的指针将不胜感激。

1 个答案:

答案 0 :(得分:1)

根据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)
 })
相关问题