nodejs / Mongo – 多个发现不起作用

仍然NooB到Node / Mongo,并坚持这一点。

我有两个孟戈collections,租户和租金。 租金收入在scheme中有租客_id。 以下function正在search所有有效租户,并为每个租户提供最新租赁文档的一些属性。 该函数的第一部分用结果填充租户对象。 一切正常。 第二个。然后开始遍历租户对象,拉出_id以在租赁查询中使用。 (join)。 问题是for循环似乎遍历并正确地打印_id,但第二个find查询似乎只打印出对象中的最后一个文档。 我只是不确定为什么会发生这种情况

提前致谢

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操作符的集合操作来简化查询,这个操作允许你在同一个数据库中执行一个左外部连接到另一个集合,以便从“joined”集合中过滤文档进行处理。

考虑运行以下pipe道:

 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) });