引用模式

时间:2018-04-15 20:50:34

标签: node.js mongodb mongoose

我有以下两种模式(诊所和用户):

const ClinicSchema = new Schema({
name: {
  type: String,
  unique: true,
  required: true
},
createdBy: {
  type: Schema.Types.ObjectId,
  ref: 'user'
},
createdAt: Date,
updatedBy: {
  type: Schema.Types.ObjectId,
  ref: 'user'
},
updatedAt: Date

});

这是用户架构

const UserModelSchema = new Schema({
email: {
  type: String,
  required: true,
},
password: {
  type: String,
  required: true,
},
firstName: {
  type: String,
  required: true,
},
lastName: {
  type: String,
  required: true,
},
roles: {
  type: [String],
  required: true,
}    

});

我想编写一个查询,用于搜索诊所名称中包含的字符串或者创建用户名称或者创建用户姓名,返回诊所名称与部门匹配的所有诊所搜索字符串或由名称创建的部分匹配搜索字符串的一部分或由姓氏创建的部分匹配搜索字符串这里是我试图解释的伪SQL替代方法:

SELECT * FROM clinics
JOIN users on clinics.createdBy = users.id
WHERE clinics.name LIKE '%STRING%'
OR users.firstname LIKE '%STRING%'
OR users.lastname LIKE '%STRING%'

过去两天我一直在寻找这个解决方案,似乎无法弄明白,更具体地说,我正在尝试将WHERE OR功能添加到以下查询中:

const clinicsQuery = Clinic.find({
  name: new RegExp(req.query.searchTerm, 'i')
});

....

const clinicsList = await clinicsQuery
  .limit(limit)
  .skip(skip)
  .populate('createdBy', ['firstName', 'lastName']);

1 个答案:

答案 0 :(得分:1)

可以使用$lookup

执行
const clinicsQuery = Clinic.aggregate([{
   $lookup:
     {
       from: 'user',
       localField: 'createdBy',
       foreignField: '_id',
       as: 'user'
     }}, 
     { $unwind: "$user"}
     {
       $match: {
         $or: [
          {"user.firstname":  new RegExp(req.query.searchTerm, 'i')}, 
          {"user.lastname":  new RegExp(req.query.searchTerm, 'i')}, 
          { name:  new RegExp(req.query.searchTerm, 'i')}
        ]
       }
     },
     {$limit: limit}
]);

用户将在"用户"结果中的字段。但是你没有猫鼬准备好的对象:/