Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

node.js - Mongoose find By condition otherwise find all ($or)

if you pass categoryId it will return category with that categoryId but if you don't pass it, I want this route to return all categories... I tried this with $or but it always returns all categories regardless of I passed categoryId or not :

await Category.find({ $or: [{ _id: categoryId }, {}] });

I can use the if statement but it takes a lot of code, can this be done cleaner?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this:

await Category.find({ _id: (categoryId || {$exists: true}) });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...