【问题标题】:Query in MongoDB that search is true; query syntax troubles在 MongoDB 中查询 search 是否为真;查询语法问题
【发布时间】:2021-07-07 02:30:06
【问题描述】:

这可能是一个令人尴尬的问题,但我正在尝试根据位置搜索和日期来呈现用户搜索。我们的profile对象的结构如下;

availability: {
    monday: { type: Boolean, default: false },
    tuesday: { type: Boolean, default: false },
    wednesday: { type: Boolean, default: false },
    thursday: { type: Boolean, default: false },
    friday: { type: Boolean, default: false },
    saturday: { type: Boolean, default: false },
    sunday: { type: Boolean, default: false },
  }

这是我的控制器;

exports.findUsersByDay = asyncHandler(async (req, res) => {
  const search = req.params.search;

  try {
    const profileList = await Profile.find({
      availability: { $in: search }
    });

    if (profileList.length > 0) {
      return res.status(200).json({ profiles: profileList });
    } else {
      return res.status(404).json({ message: "No Profiles Found" });
    }
  } catch (error) {
    return res.status(500).json({ message: error });
  }
})

如何查询配置文件对象是否将日期之一(或多个,如果作为数组向下传递)设置为 true?

【问题讨论】:

    标签: node.js typescript mongodb express


    【解决方案1】:

    您可以为此创建一个动态查询。 获取您想要的所有日子并将其与$and 一起使用:

    let findQuery = { $and : [ ]};
    let search = ['monday','thursday']; search.forEach((a)=>{
      let aName = `availability.${a}` 
    findQuery['$and'].push({
    [aName] : true
    })});
    
    const profileList = await Profile.find(findQuery);
    

    我认为使用$where 也可以完成类似的操作,但性能会受到影响。

    【讨论】:

    • 此搜索是否在可用性字段对象中?我似乎仍然遇到的问题是它没有在该字段中搜索。
    • 它返回的配置文件全部为假,默认值,但在其他字段中为真
    • 我忘记在前面添加可用性字符串。检查编辑的答案?
    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 2017-06-01
    • 2021-01-21
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多