node.js - nodejs/Mongo - 多个发现不起作用

标签 node.js mongodb

仍然是 Node/Mongo 的新手,并且坚持这一点。

我有两个 mongo 集合,Tenants 和 Rent。收租在模式中有租户 _id。以下功能正在搜索所有活跃的租户,并为每个租户提取最新租金文件的一些属性。 该函数的第一部分使用结果填充租户对象。一切正常。 第二个 .then 开始遍历租户对象,提取 _id 以在 Rent 查询中使用。 (加入)。 问题是 for 循环似乎遍历并正确打印 _id,但第二个查找查询似乎只打印出对象中的最后一个文档。我只是不确定为什么会这样

提前致谢

app.get('/chargerenttest/:date', (req,res) => {

//check date is valid
var rentChargeDate = new Date(req.params.date);
var tenant = "";
//for each active tenant



 Tenant .find({
           activeTenant : true
            })
         .then ((tenant) => {          
          if (!tenant) {
             return res.status(404).send();
           }
           console.log("found tenents")
           return tenant
          })

          .then ((tenant) => {
           for (var i in tenant) {
                console.log(i)
                console.log(tenant[i]._id)

               Rent 
                .find({
                  "paymentType" :"Rent",
                  "tenantID" : tenant[i]._id,
                  "activeEntry": true})
                .limit(1)
                .sort({datePaid: -1})
                  // sort in decending date ( latested on top)
                .then ((rent) => {
                      lastPayment = rent[0].datePaid;
                      lastAmountPaid = rent[0].amountPaid;

                      console.log("--------",i)

                      console.log("tenant",tenant[i]._id)
                      console.log("rentamount",tenant[i].rentAmount)
                      console.log("lastpayment", lastPayment)           
                  });           
             }

           })

})

最佳答案

可以通过运行聚合操作来简化您的查询,该聚合操作使用带有 $lookup 的管道 运算符,它允许您对同一数据库中的另一个集合执行左外连接,以过滤来自“已连接”集合的文档以进行处理。

考虑运行以下管道:

Rent.aggregate([
    {
        "$match": {
            "paymentType": "Rent",
            "activeEntry": true
        }
    },
    {
        "$lookup": {
            "from": "tenants",
            "localField": "tenantID",
            "foreignField": "_id",
            "as": "tenants"
        }
    },
    { "$match": { "tenants": { "$ne": [] }, "tenants.activeTenant": true } },
    //{ "$unwind": "$tenants" },
    { "$sort": { "datePaid": -1 } },
    { "$limit": 1 }     
]).exec((err, rent) => {
    if (err) throw err;

    lastPayment = rent[0].datePaid;
    lastAmountPaid = rent[0].amountPaid;
    tenant = rent[0].tenants[0];

    console.log("tenant",tenant._id)
    console.log("rentamount",tenant.rentAmount)
    console.log("lastpayment", lastPayment) 
});

关于node.js - nodejs/Mongo - 多个发现不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43067909/

相关文章:

javascript - 从 SequelizeJS 中的表中选择特定属性

python - 使用 python 转储和恢复 mongo db

node.js - 如何配置WebStorm识别现有项目中的 Node ,错误: unresolved function require

node.js - Nodejs : Failed to load gRPC binary module because it was not installed for the current system

node.js - 在 webpack 构建期间登录到 Node 控制台或调试

mongodb - 是否可以通过 $lookup 将字符串与 ObjectId 进行比较

python - 无法从 JSON 反序列化 PyMongo ObjectId

mongodb 2.4.9版本,无法启动mongodb服务

php - Javascript 函数在使用 PHP 的 mongoDB 中无法正常工作

javascript - Node.js、Npm、 Node 。套餐区别?