简体   繁体   English

使用 NodeJS 从 MongoDB 中的集合中获取数据

[英]get Data from a collection in MongoDB using NodeJS

I am trying to get data from Mongo DB by filtering a nested object.我试图通过过滤嵌套对象从 Mongo DB 获取数据。

the collection structure is :集合结构是:

    { 
   "id":"8820624457",
   "type":"CreateEvent",
   "actor":{ 
      "id":27394937,
      "login":"Johnson0608",
      "display_login":"Johnson0608",
      "gravatar_id":"",
      "url":"https://api.github.com/users/Johnson0608",
      "avatar_url":"https://avatars.githubusercontent.com/u/27394937?"
   },
   "repo":{ 
      "id":163744671,
      "name":"Johnson0608/test",
      "url":"https://api.github.com/repos/Johnson0608/test"
   },
   "payload":{ 
      "ref":"master",
      "ref_type":"branch",
      "master_branch":"master",
      "description":null,
      "pusher_type":"user"
   },
   "public":true,
   "created_at":"2019-01-01T15:00:00Z"
}

I am trying to get data by repo id.我正在尝试通过 repo id 获取数据。 my code is :我的代码是:

collection.find({'repo.id':id}).toArray(function(err, docs) {
    console.log(id);
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  res.status(200).json({docs});
  callback(docs);
});

but I am getting empty array, would be grateful is someone can point me to the right direction但我得到了空数组,如果有人能指出我正确的方向,我将不胜感激

MongoDB compares types before values. MongoDB 在值之前比较类型 If your id comes from req.params it's probably passed as string while repo.id seems to be a number.如果您的id来自req.params它可能作为字符串传递而repo.id似乎是一个数字。 Try to convert your value to number:尝试将您的值转换为数字:

const id = +req.params.repoId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM