猫鼬聚合,不能动态添加someField:{$ not;空值 } [英] Mongoose aggregate, can't dynamically add someField: { $not; null }
问题描述
我正在根据用户输入的条件生成查询.用户可以通过选择来设置自定义过滤.
I am generating a query based on user's input as to conditions. User can set custom filtering by making selections.
到目前为止,一切都还好.例如,这有效:
All is okay, so far. For example, this works:
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或不为null的查询.像这样:
This builds the query nicely and runs well. Now, however, I have a slightly different requirement to add to the list. I want to also include a possible query for null or not null. Something like this:
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!
}
}
当我运行此代码时,将状态设置为开帐单",则不会引发任何错误.但是,也不会返回事务".引发错误:无法读取未定义的属性'length'."
When I run this code setting the status to "billed," no error is thrown. However, no "transactions" are returned, either. An error is thrown: "Cannot read property 'length' of undefined."
如何修复损坏的部分?
顺便说一句,总共有5条记录,并且有1条记帐.当它起作用时,我应该收到1条记录.
By the way, there are 5 records total, and 1 is billed. When it works, I should receive the 1 record.
推荐答案
有一个特殊的 $ type 运算符,可用于检查属性类型.因此,如果您的集合中有明确的null,它们的类型将为10
.类型代码的完整列表在此处.因此,要检查属性是否不等于null
,可以使用以下查询.
There's a special $type operator which allows you to check property type. So if you have explicit nulls in your collection, they will be of type 10
. Full list of type codes here. So to check if a property is not equal to null
you can use following query.
db.transactions.aggregate([
{
$match: {
billId: { $not: { $type: 10 } }
}
}
])
这篇关于猫鼬聚合,不能动态添加someField:{$ not;空值 }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!