gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:41:04 26 4
gpt4 key购买 nike

仍然是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com