node.js - 如何从 Mongoose 的填充模型中查找文本?

标签 node.js mongodb mongoose aggregation-framework

我们有两种型号:

  1. 用户
   const userSchema = new mongoose.Schema({
       name: {
           type: String
       },
       email: {
           type: String
       },
       vehicleId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'vehicle'
       }
   })
  • 车辆
  •     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.
    

    您能帮助我们吗?如何实现这一目标?

    最佳答案

    您可以首先对车辆模型运行查询以获取名称为粉色的所有车辆

    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不为空,则vehicles[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:}}
    ]})
    

    关于node.js - 如何从 Mongoose 的填充模型中查找文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488375/

    相关文章:

    javascript - 将 Bluebird Promisifyall 与 Mongoose 结合使用

    javascript - 尝试使用 .find() 查看我的集合时 Mongo 出现问题

    node.js - req.body 不能作为数组读取

    node.js - 用哈巴狗、Postgres 和适当的 MVC 表达

    c# - Mongo DB中的Upserting和Id问题

    javascript - $and with sub $and 在 mongo 和 mongoose 中没有产生预期结果

    javascript - Angular - $routeParams.itemID 用于加载domain.com/:itemID ALMOST WORKING?

    永久使用时的 Node.js 参数

    css - Bootstrap 响应式导航栏在浏览器中缩放时有效,但在我的手机上无效

    javascript - Mongoose 枚举数