首页 > 解决方案 > 如何在猫鼬中从填充模型中查找文本?

问题描述

我们有两个模型:

  1. 用户
   const userSchema = new mongoose.Schema({
       name: {
           type: String
       },
       email: {
           type: String
       },
       vehicleId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'vehicle'
       }
   })
  1. 车辆
    const vehicleSchema = new mongoose.Schema({
       name: {
           type: String
       },
       color: {
           type: String
       }
   })

现在,我们必须从用户(姓名,电子邮件)和车辆(姓名,颜色)中找到用户输入

- If user search "pink" then we have to find that if any user has with name, email or them vehicle include "pink" keyword or not.
- If string match from reference model then we have to return whole record.

你能帮助我们,如何实现这一目标?

标签: node.jsmongodbmongooseaggregation-framework

解决方案


您可以先在 Vehicle 模型上运行查询,以获取名称为 pink 的所有车辆

let vehicleIds=await Model.Vehicle.aggregate([
 {$match:{$or:[
             {name:{$regex:"pink",$options:"i"}},
             {color:{$regex:"pink",$options:"i"}
 ]}},
 {$group:{_id:null,ids:{$push:"$_id"}}}    
])

此处如果 vehicleIds 不为空,则车辆 [0].ids 将具有名称或颜色为粉红色的 vehcileIds

let vehcileIds=[]
if(vehicles.length) vehcileIds=vehicles[0].ids

在上述查询运行后,在用户模型中运行另一个查询

let users= await Models.User.find({$or:[
{name:{$regex:"pink",$options:"i"}},
{email:{$regex:"pink",$options:"i"}
{vehicleId:{$in:}}
]})

推荐阅读