猫鼬,如何使用两个或多个条件执行find() [英] Mongoose, how to do a find() with two or conditions

查看:265
本文介绍了猫鼬,如何使用两个或多个条件执行find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找所有具有标题或包含正则表达式的desc的文档(有效),然后进一步对其进行过滤,以仅包含将"private"标志设置为的文档false或将用户"字段设置为给定的userId.

I'm trying to do a find which will get all documents which has a title or desc that contains the regular expression (which works) and then filter it further to only contain documents which either have the "private" flag set to false or the "user" field set to the given userId.

到目前为止,这是我正在尝试的...

Here's what I'm trying so far...

FCSet.find({}, {"flashCards":0}).or([{ 'title': { $regex: re }}, { 'desc': { $regex: re }}]).or([{ 'private': false}, { 'user': 'userId'}]).sort('title')

这应该只返回6行,但返回56.如果我取出第二个or(),那么它可以按标题/描述进行过滤.我猜我正在以错误的方式进行操作.

This should only be returning 6 rows but it's returning 56. If I take out the 2nd or() then it works for filtering by title/desc. I'm guessing that I'm going about it the wrong way.

有人可以帮助我弄清楚如何正确执行此操作吗?

Can someone help me figure out how to do this correctly?

推荐答案

您必须将OR放入AND:

FCSet.find( 
    { "flashCards": 0 }, 
    $and: [ 
        { 
            $or: [
                { 'title': { $regex: re } }, 
                { 'desc': { $regex: re } }
            ]
        },
        {
            $or: [ 
                { 'private': false }, 
                { 'user': 'userId' } 
            ]
        }
    ]
).sort('title')

这篇关于猫鼬,如何使用两个或多个条件执行find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆