【问题标题】:Nodejs mongodb returns empty array when it shouldn'tNodejs mongodb 不应该返回空数组
【发布时间】:2017-05-18 01:48:01
【问题描述】:

我在 mongodb 用户和评论中有 2 个集合,模式是用户(_id,名字,姓氏,电子邮件,密码)和评论(_id,reviewForID,reviewdByID,reviewText),我有一个我将使用的快递方法返回用户和与该用户关联的所有评论,但是当我尝试查询评论集合时,有时会返回一个空数组。错误发生在 getReviews() 函数中,我已经注释了导致错误的行。我不知道是什么导致了错误以及为什么它只在我添加 toString() 时才起作用

注意:getReview() 函数的目的是从数据库中获取所有评论的数组,并将该数组附加到 userA 对象,然后将 userA 对象作为响应发送给客户端

  var ObjectId = require('mongodb').ObjectID; //used to query objs by id     

 //parameters are (userid)
 app.post('/getUserInfo', function (req, res)
 {
   var queryObj = { _id: new ObjectId(req.body.userid)};

   MongoClient.connect(url, function (err, db)
   {
     if (err)
     {
        console.log('Unable to connect to the mongoDB server. Error:', err);
     }
     else //HURRAY!! We are connected. :)
     {
        var collection = db.collection('User');

        collection.findOne(queryObj, function (err, resultDocument)
        {
           if (err)
           {
              console.log(err);
           }
           else if (resultDocument)
           {
             getReviews(resultDocument,res);
           }
           else
           {
              res.send({"result":"failed"});
           }

           db.close();//Close connection
        });//collection.find end
     }//else
   });//MongoClient.connect end
 });//get user info end

 //find all the reviews and add them to the object userA
 function getReviews(userA,response)
 {


   //var queryObj = { reviewForID: userA._id }; returns empty array
   //var queryObj = { reviewForID: new ObjectId(userA._id) }; returns empty array
   //var queryObj = { reviewForID: userA._id.toString() }; returns correct documents

   MongoClient.connect(url, function (err, db)
   {
      if (err)
      {
         console.log('Unable to connect to the mongoDB server. Error:', err);
      }
      else //HURRAY!! We are connected. :)
      {
          var collection = db.collection('Review');

          collection.find(queryObj).toArray(function (err, result)
          {
             if (err)
             {
                console.log(err);
             }
             else
             {
                response.send(result);
             }

             db.close();//Close connection
         });//coolection.find end

      }//else
  });//MongoClient.connect end
 }//get reviews end

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    看起来 Review 集合中的 reviewForID 是 String 类型的字段,在该集合中存储 String 值,而 User 集合中的 _id 显然是 ObjectId 类型,因此您无法获取数据,因为存在类型不匹配.

    当调用toString时,它基本上返回与reviewForID的String类型匹配的String值,这就是它与toString一起使用的原因。

    也许您可以将 reviewForID 存储为 ObjectId 类型以进行直接匹配。

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2019-04-15
      相关资源
      最近更新 更多