首页 > 解决方案 > Mongo DB / Mongoose 条件包含搜索

问题描述

我有一个可能涉及复杂查询的简单功能。我想让用户只显示给他们已经批准在我的站点中找到他们的成员。

问题是我不知道如何添加条件然后在查询的用户中查询。

  1. 用户调用 find。
  2. 如果搜索的用户选择了“仅批准”。
  3. 检查搜索用户是否在他们的批准列表中。

我正在使用 NodeJS 和 Mongoose 来进行我的发现。请帮忙。

架构如下:

const ProfileSchema = new mongoose.Schema({
  userDOBs: {
    type: [Date],
    required: true
  },
  gender: {
    type: String,
    required: true
  },
  active: {
    type: Boolean,
    default: true
  },
  discoverySettings: {
    approvedOnly: {
      type: Boolean,
      default: false
    }
  },
  blockedProfileIDs: {
    type: [mongoose.Schema.Types.ObjectId],
    ref: "Profile"
  },
  approvedIDs: [
    {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "Profile"
    }
  ]
});

下面查询:

const profiles = await Profile.find({
        $and: [
          {
            _id: {
              $ne: req.user.profileID,
              $nin: doNotDisplayList
            },
            "loc.loc": {
              $nearSphere: [long, lat],
              $maxDistance: maxDistance
            },
            userDOBs: {
              $lt: moment().subtract(filter.searchParams.ageRange[0], "years"),
              $gt: moment().subtract(filter.searchParams.ageRange[1], "years")
            },
            active: true,
            "discoverySettings.visible": true,
            blockedProfiles: {
              $ne: req.user.profileID
            }
          }
        ]
      })
        .sort({
          updatedAt: -1
        })
        .limit(limit)
        .skip(skip);

标签: node.jsmongodbmongooseecmascript-6mongodb-query

解决方案


推荐阅读