【发布时间】:2018-01-04 05:52:09
【问题描述】:
我正在根据用户输入的条件生成查询。用户可以通过选择来设置自定义过滤。
到目前为止,一切都很好。例如,这有效:
exports.getJoinedTransactions = function(firmId, page, pageSize, billerId, matterId, words, billingStatus, 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;
}
....
myAggregate = [
{ $sort: { date: -1 } },
{
$match: query
},
....
Transactions.aggregate(myAggregate).exec( function(err, transactions) {
if (err) {
console.log(err);
}
someVar = transactions.length;
....
这很好地构建了查询并且运行良好。但是,现在我有一个稍微不同的要求要添加到列表中。我还想包括对 null 或 not null 的可能查询。像这样的:
if (typeof billingStatus === "string" && billingStatus != "") {
if (billingStatus === "billed") {
query.billId = { $not: null } ; <-- This does not work.
} else if (billingStatus === "unbilled") {
query.billId = null; <-- This works!
}
}
当我运行此代码并将状态设置为“计费”时,不会引发错误。但是,也不会返回任何“交易”。抛出错误:“无法读取未定义的属性‘长度’。”
如何修复损坏的部分?
编辑:顺便说一下,总共有 5 条记录,其中 1 条已计费。当它起作用时,我应该会收到 1 条记录。
【问题讨论】: