[英]Mongoose search query with regex not returning expected results with multiple conditions and population
export const searchPost = async (req: any, res: Response) => {
try {
const searchQuery = req.params.query;
const page = req.query.page || 1;
const limit = req.query.limit || 10;
const skip = (page - 1) * limit;
const posts = await Post.find({
$or:
[
{ content: { $regex: searchQuery, $options: 'i' } },
{ location: { $regex: searchQuery, $options: 'i' } },
{ 'user.fullName': { $regex: searchQuery, $options: 'i' } },
{ 'user.username': { $regex: searchQuery, $options: 'i' } },
{ 'group.name': { $regex: searchQuery, $options: 'i' } }
]
})
.populate('user')
.populate('group')
.skip(skip)
.limit(limit)
.sort({ createdAt: -1 });
res.json(posts);
} catch (err) {
console.log(err);
return res.status(500).json({ message: 'Something went wrong!' });
}
};
const PostSchema = new Schema(
{
content:
{
type: String,
required: true
},
location:
{
type: String
},
image:
{
type: String
},
user:
{
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
group:
{
type: Schema.Types.ObjectId,
ref: 'Group'
},
comments:
[
{
type: Schema.Types.ObjectId,
ref: 'Comment'
}
],
likesCount:
{
type: Number,
default: 0
},
likesUsers:
[
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
},
{ timestamps: true }
);
const Post = mongoose.model('Post', PostSchema);
export default Post;
const UserSchema = new Schema(
{
fullName:
{
type: String,
required: true,
index: true
},
username:
{
type: String,
required: true,
index: true
},
email:
{
type: String,
required: true,
unique: true
},
password:
{
type: String,
required: true
},
profileImg:
{
type: String,
default:
'https://res.cloudinary.com/dyfm31f1n/image/upload/v1675059905/fit-fiesta/placeholders/blank-profile-picture-gdb207bae8_1280_zymz7e.png'
},
coverImg:
{
type: String,
default:
'https://res.cloudinary.com/dyfm31f1n/image/upload/v1675059731/fit-fiesta/placeholders/bg_qr4vtm.jpg'
},
location:
{
type: String
},
weight:
{
type: Number
},
height:
{
type: Number
},
targetWeight:
{
type: Number
},
groups:
[
{
type: Schema.Types.ObjectId,
ref: 'Group'
}
],
events:
[
{
type: Schema.Types.ObjectId,
ref: 'Event'
}
],
posts:
[
{
type: Schema.Types.ObjectId,
ref: 'Post'
}
],
connections:
[
{
type: Schema.Types.ObjectId,
ref: 'User'
}
],
pendingConnections:
[
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
},
{ timestamps: true }
);
Post model 引用了一個 User model 和一個 Group model。該方法使用 populate 方法用它們的相應數據填充這些引用。 查詢結果按創建時間降序排列,並作為響應發送給客戶端。
在 searchPost API 中,它在使用正則表達式查找時不考慮用戶關系字段,例如 user.username 和 user.fullName 或 group.name
find
、 skip
、 limit
和sort
由服務器端的 mongodb 數據庫執行。 然后將結果發送回 mongoose,在那里通過提交其他查詢來執行populate
。
在數據庫的“post”文檔中,“user”和“group”字段包含一個 ObjectId,而不是 object,因此字段“user.fullName”、“user.username”和“group.name”不不存在,因此不匹配。
為了在數據庫服務器上過濾這些字段,您需要使用aggregate
和單獨的$lookup階段來檢索用戶和組文檔,以便服務器考慮這些字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.