【问题标题】:Mongoose aggregate, can't dynamically add someField: { $not; null }Mongoose 聚合,不能动态添加 someField: { $not;无效的 }
【发布时间】: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 条记录。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    有一个特殊的$type 运算符允许您检查属性类型。因此,如果您的集合中有明确的空值,它们将是10 类型。类型代码的完整列表here。因此,要检查属性是否不等于 null,您可以使用以下查询。

    db.transactions.aggregate([
        {
            $match: {
                billId: {  $not: { $type: 10 } }  
            }
        }
    ])
    

    【讨论】:

    • 聪明!谢谢!
    猜你喜欢
    • 2016-11-17
    • 2018-05-10
    • 2021-07-21
    • 1970-01-01
    • 2020-12-08
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多