我有一個查找查詢,例如:
person = await PersonSchema.find({
givenName: (gn == 'none') ? {} : gn,
lastName: (ln == 'none') ? {} : ln,
placeOfBirth: (pob == 'none') ? {} : pob,
dob: { $regex: (dob == 'none') ? {} : dob }
});
基本上,如果這些欄位中的任何一個等于“無”,我想回傳所有值...基本上將其從查詢中洗掉...有人知道該怎么做嗎?
或者甚至想到解決這個問題的另一種方法?
uj5u.com熱心網友回復:
您應該使用 $and 以防您的兩個欄位不等于“無”。也許像這樣;
const filter = [{}] // if all field equal none, default $and
gn !== 'none' && filter.push({givenName: gn})
ln !== 'none' && filter.push({lastName: ln})
pob !== 'none' && filter.push({placeOfBirth: pob})
dob !== 'none' && filter.push({dob: dob})
person = await PersonSchema.find({$and : filter});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490197.html
上一篇:Mongoose-Error.ValidationError和Error.ValidatorError之間的區別
