我讨厌这个答案,我希望有人会发布一个更好的答案,但我已经在网上冲浪,但没有运气.
我所能找到的唯一方法是在聚合中使用$lookup
方法.
因此,您必须将您的代码从呼叫.find()
更改为.aggregate()
.
这不是悲伤的消息,它是伟大的,稳定的,没有任何问题.
但我讨厌它,因为它将改变您在代码中可能遵循的一些模式.
const search = req.query.search || "";
const cheques = await Cheque
.aggregate([
{
$lookup: { // similar to .populate() in mongoose
from: 'payees', // the other collection name
localField: 'payee', // the field referencing the other collection in the curent collection
foreignField: '_id', // the name of the column where the cell in the current collection can be found in the other collection
as: 'payee' // the field you want to place the db response in. this will overwrite payee id with the actual document in the response (it only writes to the response, not on the database, no worries)
},
{ // this is where you'll place your filter object you used to place inside .find()
$match: {
isCancelled: false,
dueDate: { $gte: sinceDate, $lte: tillDate }
'payee.branch': 'YOUR_FILTER', // this is how you access the actual object from the other collection after population, using the dot notation but inside a string.
}
},
{ // this is similar to .select()
$project: {_id: 1, serial: 1, dueDate: 1, value: 1, payee: 1}
},
{
$unwind: '$payee' // this picks the only object in the field payee: [ { payeeDoc } ] --> { payeeDoc }
}
])
.skip(page * limit)
.limit(limit)
.sort({ dueDate: -1, serial: 1 })
请注意,您不能再像以前在.find()
上那样在模型查询上链接.select()
和.populate()
,因为现在您使用的是.aggregate()
,它返回Mongoose中的不同类实例.
- 如果愿意,您可以调用
.projcet()
,而不是在聚合数组中调用,但据我所知,您不能使用.select()
方法.
我对这个问题的基于意见的解决方案是将您需要过滤的收款人信息包括在支票集合中.
在我的管理员中,当我为了我的用户--角色和权限--而进行过滤时,就会发生这种情况,这样别人就看不到别人看到的东西了.
这由您决定,但这会在以后您想要生成报告时变得更容易(我假设您正在使用支付服务).