猫鼬忽略查找中的列,如果该值为空

时间:2020-08-19 17:35:50

标签: javascript mongoose

假设我有一个猫鼬模型和一个基于偶然性的值

const findUser = async (username, email) => {
  let foo = null
 
  if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"

  UserModel.find({ "username": username, "email": email, "winner": foo === null ? 'EXCLUDE THIS SEARCH VALUE' : foo
}

^ This is some real code, in combination with some pseudo code ^

我可以这样实现:

const findUser = async (username, email) => {
  let foo = null
 
  if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"

  let result;
  if(foo === null)
    result = await UserModel.find({ "username": username, "email": email });
  else
    result = await UserModel.find({ "username": username, "email": email, "winner": foo });
  // ^^ Now I have to type the same thing all over again..
  // I'm wondering if there is a way to include it conditionally?
}

但是这里的问题是我必须再次输入相同的内容,只是要包含另一个字段。有没有一种方法可以在搜索中适当地包含一列?

2 个答案:

答案 0 :(得分:1)

可能有一种更简单/更好的方法来实现此目的,但是在这种情况下,我要做的就是构建一个像这样的对象。

const findUser = async (username, email) => {
  let foo = null

  let query = {
   username,
   email
  }
 
  if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"

  if (foo != null) {
    query.winner = foo;
  }

  UserModel.find(query);
}

基本上,创建一个默认对象,该对象中将始终带有您的属性。然后检查您的foo值是否不为null。并且,如果它不为null,则将其添加到查询中,然后将该查询对象传递到查找中。

答案 1 :(得分:1)

您可以将查询提取到变量中,然后根据foo的值进行操作。

const findUser = async (username, email) => {
   let foo = null

   if (Math.random() > 0.5) foo = "hi"

   const query = { username, email }

   if (foo) {
      query.winner = foo
   }

   const result = await UserModel.find(query)
}