V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cc7756789
V2EX  ›  Node.js

mongoose 条件查询时如何实现判断

  •  
  •   cc7756789 · 2015-10-24 19:19:37 +08:00 · 3185 次点击
    这是一个创建于 3112 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Model.find()
        .where('type', one)
        .where('published', two)
        .where('nation', three)
        .sort({'field': -1})
        .exec(callback)
    

    one, two, three 有可能是 0, 代表搜索全部, 其值由前端传入, 但是数据库中每个字段由 1 开始, 我想要类似的效果

    Model.find()
        if (one != 0) {
            .where('type', one)
        }
        if (two != 0) {
            if (two != -1) {
                .where('published', two)
            } else {
                .where('published').lte(2010)
            }
        }
        if (three != 0) {
        .where('nation', three)
        } 
        .sort({'field': -1})
        .exec(callback)
    

    这样的结果在 mongoodse 该如何实现

    1 条回复    2015-10-24 19:32:22 +08:00
    cdxem713
        1
    cdxem713  
       2015-10-24 19:32:22 +08:00 via iPhone
    你自己构造一个 object,自己组条件不就好了么
    var query = {}
    (one !=0) && (query['type']=one);
    ......
    Model.find(query).sort(...).exec...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2232 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 02:19 · PVG 10:19 · LAX 19:19 · JFK 22:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.