$或搜索虚拟填充mongoose

时间:2018-02-15 19:27:36

标签: mongodb mongoose mongoose-populate

我正在尝试为我的一个模式创建搜索功能。此架构有4个虚拟填充映射,我也想搜索。我可以在我的虚拟填充上使用匹配,但这将限制我的所有结果,除非满足这些结果。

multiSchema: {

     plat: String,
     k_1: String,
     K_2: String
}

multiSchema.virtual({
     ref: 'singles',
     localField: 'k_1',
     foreignField: 'singles_special_id',
     justOne: true
})

multiSchema.virtual({
     ref: 'singles',
     localField: 'k_2',
     foreignField: 'singles_special_id',
     justOne: true
})

singleSchema: {
    single_special_id,
    n: String
    //
    **otherfields**
    ////
}

multi.find({
    $or: [{
        plat: {
          $regex: input,
          $options: 'i'
        }
      },
      {
        k_1: {
          $regex: input,
          $options: 'i'
        }
      },
      {
        k_2: {
          $regex: input,
          $options: 'i'
        }
      }
    ]
  }).lean()
  .populate({
    path: 'k_p_1',
    match: {
      $or: [{
        n: {
          $regex: input,
          $options: 'i'
        }
      }]
    }
  })
  .populate({
    path: 'k_p_2',
    match: {
      $or: [{
        n: {
          $regex: input,
          $options: 'i'
        }
      }]
    }
  })
  .populate({
    path: 'h_p_1',
    match: {
      $or: [{
        n: {
          $regex: input,
          $options: 'i'
        }
      }]
    }
  })
  .populate({
    path: 'h_p_2',
    match: {
      $or: [{
        n: {
          $regex: input,
          $options: 'i'
        }
      }]
    }
  })
  .exec()

示例数据:

multi: {
   plat: "foo"
   k_1: "hello",
   k_2: "world"
}

single: {
   singles_special_id: "hello"
   n: "bar"
}

如果我尝试搜索bar,它不会返回任何多个模式,因为搜索多个模式值后可能会出现填充。

0 个答案:

没有答案