【问题标题】:Node.js and MongoDB Use results from one query in anotherNode.js 和 MongoDB 在另一个查询中使用一个查询的结果
【发布时间】:2013-08-12 21:17:00
【问题描述】:

我创建了一个 node.js 模块,它已经可以使用 find 查询 MongoDB 的一组文档并将这些结果输出到 JSON。我的问题是,知道 node.js 是异步的,我如何使用此查询(项目)的结果来创建一个查询,该查询可以返回到 MongoDB 以查找另一组文档。此查询基本上返回一个员工 ID 列表,可用于查询包含这些员工信息的文档(即名字、姓氏等)。然后将这些结果输出为 JSON。第一个查询基本上是说,给我一个特定用户可以查看的所有员工。然后,我需要获取员工 ID 并对包含这些个人信息的另一组文档进行查询,如下所示。

这是两个文档架构:

员工

{
"_id" : ObjectId("5208db78ecc00915e0900699"),
"clientId" : 1,
"employeeId" : "12345",
"lastName" : "DOE",
"firstName" : "JOHN",
"middleName" : "A",
"badge" : "8675309",
"birthDate" : "10/12/1978"
}

员工可以访问的用户(用户缓存)

{
"_id" : ObjectId("520920a99bc417b7c5e36abf"),
"clientSystem" : "SystemX",
"customerNumber" : "1",
"clientUserId" : "jdoe3",
"securityCode" : "authorize",
"employeeId" : "12345",
"creationDate" : "2013-Aug-12 13:51:37"
}

这是我的代码:

exports.employeeList = function(req, res) {
    console.log(req.params);
    var clientSystem = req.query["clientSystem"];
    var clientUserId = req.query["clientUserId"];
    var customerNumber = req.query["customerNumber"];
    var securityCode = req.query["securityCode"];

 if (clientSystem != null && clientUserId != null && customerNumber != null && securityCode != null){
    db.collection('ExtEmployeeList', function(err, collection){
        collection.find({'clientSystem': clientSystem, 'clientUserId':clientUserId, 'customerNumber':customerNumber, 'securityCode': securityCode}).toArray(function (err, items){
             console.log(items);
             res.jsonp(items);
        });//close find
     });//close collection
}//close if
else {
   res.send(400);
}//close else
};//close function

【问题讨论】:

  • 2 条建议 -- 使用$in 根据员工 ID 检索一组文档,并查看 Mongoose,因为它使此类操作变得简单。

标签: node.js mongodb mongodb-query mongodb-java node.js-connect


【解决方案1】:

您想要做的事情是可能的,但可能不是 Mongo 最有效的用途。我倾向于围绕数据的实际使用方式来设计 Mongo 文档。因此,如果我需要将用户名显示在我可以查看的用户列表中,我会嵌入该数据,这样我就不必多次往返 mongo 来获取我需要的所有信息。我会做如下的事情:

{
  "_id" : ObjectId("520920a99bc417b7c5e36abf"),
  "clientSystem" : "SystemX",
  "customerNumber" : "1",
  "clientUserId" : "jdoe3",
  "securityCode" : "authorize",
  "employeeId" : "12345",
  "creationDate" : "2013-Aug-12 13:51:37"
  "employee": {
    "_id" : ObjectId("5208db78ecc00915e0900699"),
    "clientId" : 1,
    "employeeId" : "12345",
    "lastName" : "DOE",
    "firstName" : "JOHN",
    "middleName" : "A",
    "badge" : "8675309",
    "birthDate" : "10/12/1978"
  }
}

是的,您正在复制数据,但您正在显着减少到数据库的往返次数。这通常是您在使用基于文档的数据库时所做的权衡,因为您无法连接表。

【讨论】:

  • 我采纳了您的建议并修改了我的架构。我现在可以进行一次查询来获得我需要的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多