这是我的查询结构,用于获取已连接的事务,将contactId连接到contact._id等。它工作正常。请注意顶部的 $ match:query 。
myAggregate = [
{ $sort: { date: -1 } },
{
$match: query
},
{
$lookup: {
from: "contacts", // collection name in db
localField: "contactId",
foreignField: "_id",
as: "contact"
}
},
{
$unwind: "$contact"
},
{
$lookup: {
from: "matters", // collection name in db
localField: "matterId",
foreignField: "_id",
as: "matter"
}
},
{
$unwind: "$matter"
}
];
在上面的聚合之前,是包含用于形成查询的参数的函数。这是它的声明(注意参数列表中的 contactId ):
// Get Billing Entries according to filter criteria.
exports.getJoinedTransactions = function(firmId, page, pageSize, billerId, contactId, matterId, words, billingStatus, dateBeginning, dateEnding, transactionType, cb) {
let firmIdToObjId = new mongoose.Types.ObjectId(global.user.firmId);
let query = { firmId: firmIdToObjId };
if ( typeof billerId === "object" ) {
billerId = new mongoose.Types.ObjectId(billerId);
query.contactId = billerId;
}
if ( typeof matterId === "object" ) {
matterId = new mongoose.Types.ObjectId(matterId);
query.matterId = matterId;
}
<-- I need to add a query property of contactId here.
if (type of...
....
从上述连接操作返回的主要记录是事务。我需要查询事务以查看其联接事项(外部集合)的contactId是否与作为参数发送的contactId匹配。
有点像:
if ( typeof query.matter.contactId === "object" ) {
contactId = new mongoose.Types.ObjectId(contactId);
query.matter.contactId = contactId;
}
但我只是试过这个,但它并没有奏效。我明白了:无法设置属性&#39; contactId&#39;未定义的。
答案 0 :(得分:1)
您将需要另一个带有额外匹配阶段的查询参数。
像query2 = {"matter.contactId": contactId}
之类的东西,在最后一个展开阶段之后匹配像{$match: query2 }
这样的阶段。另外,将if条件更改为typeof contactId === "object"
。
if ( typeof contactId === "object" ) {
contactId = new mongoose.Types.ObjectId(contactId);
query2 = {"matter.contactId": contactId}
}
和
myAggregate = [
....
{
$match: query
}
....
{
$unwind: "$matter"
},
{
$match: query2
}
];