How to ignore undefined values in Mongoose aggregate match? #14547
Unanswered
somersby10ml
asked this question in
Q&A
Replies: 1 comment
-
Unfortunately Mongoose doesn't export anything quite like this. Your best bet would be to write an function omitUndefined(val) {
const keys = Object.keys(val);
for (let i = 0, len = keys.length; i < len; ++i) {
(val[keys[i]] === void 0) && delete val[keys[i]];
}
} We should export an |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a question regarding Typescript and Mongoose.
I need to use the
aggregate
function in a specific scenario. In thematch
part of theaggregate
, I tried using{ a: 11, b: undefined }
, but it seems to search fora == 11 and b == undefined
. However, what I want is to ignore the fields withundefined
values.I'd like to find a good approach to achieve this without dynamically creating the query. For example, let's say I have 5 fields in the database. I want to perform a search based on user input. Consider the following:
In this case, I want to ignore the undefined fields and have the query result in a == 'aa' and b == 'bb' and d == '11'.
When using Prisma, I could do something like
db.user.findMany({ a, b, c, d, e, ... });
and if any field was undefined, it would be ignored and filtered accordingly.Is there a similar functionality, option, or library available in Mongoose to achieve this?
Beta Was this translation helpful? Give feedback.
All reactions