跳到主要内容
CNode

mongoose find 可选查询

问答
Ccllgeek发布于 9 年前最后回复 9 年前
1248460
Library.find({category:category,subCategory:subCategory},(err,library)=>{
      if(err){
        console.log(err);
      }
      res.json({library})
    })********

上面 的代码 如果我想 subCategory 前端没传我就不查询这个字段,传了就查询 怎么写呢 ,谢谢各位了 我想到的是之前在外面加一层判断

if(subCategory){
  ....
}else{
  ...
}

但这样有点别扭啊

查看回复

回复 (12)

C
cllgeek#129 年前

@Matrixbirds 谢谢,

M
Matrixbirds#119 年前

在schema里扩展

LibrarySchema.query.andCategory = function (category) {
  if (category) return this.where({ category });
  return this;
}
LibrarySchema.query.andSubCategory = function (subCategory) {
  if (subCategory) return this.where( { subCategory } );
  return this;
}
Library.find().andCategory(category).andSubCategory(subCategory).then(result => {
   // handle record
});
M
Matrixbirds#109 年前

试试query.method?

C
cllgeek#99 年前
引用 Torres5000用正则啊

@Torres5000 怎么正则

N
nnliang#79 年前

三元运算符即可

T
Torres5000#69 年前

用正则啊

G
godghdai#59 年前

var where={category:"abc"},subCategory="343"; console.dir((subCategory&&(where["subCategory"]="abc"),where));

C
cllgeek#49 年前
引用 xiaoyu311我会

@xiaoyu311 求解答啊

D
derams#39 年前

e

X
xiaoyu311#29 年前

我会

C
cllgeek#19 年前

没人来解答 ^_^

参与回复

登录后即可参与回复。登录