Reputation: 348
I have the following 2 schemas (Clinic and User):
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
});
And Here is the user Schema
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,
}
});
I want to write a query that will search a string that is contained in the clinic name OR createdBy(user) name OR createdBy(user) last name, and return all the clinics where either the clinic name matches part of the search string OR the created by name matches part of the search string OR the created by last name matches part of the search string here is the pseudo SQL alternative of what I am trying to explain:
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%'
I have been searching for this solution for the past 2 days and can't seem to be able to figure it out, more specifically I am trying to add the WHERE OR functionality to the following query:
const clinicsQuery = Clinic.find({
name: new RegExp(req.query.searchTerm, 'i')
});
....
const clinicsList = await clinicsQuery
.limit(limit)
.skip(skip)
.populate('createdBy', ['firstName', 'lastName']);
Upvotes: 0
Views: 70
Reputation: 5212
It can be performed with a $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}
]);
User will be in "user" field in the result. But you won't have a mongoose ready object :/
Upvotes: 1