简体   繁体   English

Mongoose 使用正则表达式的搜索查询未返回具有多个条件和人口的预期结果

[英]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!' });
    }
};

Post Modal后模态

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;

User Model用户 Model

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 }
);

The Post model has a reference to a User model and a Group model. The method populates these references with their corresponding data using the populate method. Post model 引用了一个 User model 和一个 Group model。该方法使用 populate 方法用它们的相应数据填充这些引用。 The result of the query is sorted in descending order of creation time and sent as a response to the client.查询结果按创建时间降序排列,并作为响应发送给客户端。

Here in searchPost API its not considering user relation fields such as user.username and user.fullName or group.name while finding with regex在 searchPost API 中,它在使用正则表达式查找时不考虑用户关系字段,例如 user.username 和 user.fullName 或 group.name

The find , skip , limit , and sort are performed by the mongodb database on the server side. findskiplimitsort由服务器端的 mongodb 数据库执行。 The result is then sent back to mongoose where the populate is performed by submitting additional queries.然后将结果发送回 mongoose,在那里通过提交其他查询来执行populate

In the 'post' document in the database, the 'user' and 'group' fields contains an ObjectId, not an object, so the fields `user.fullName', 'user.username', and 'group.name' don't exist, and therefore don't match.在数据库的“post”文档中,“user”和“group”字段包含一个 ObjectId,而不是 object,因此字段“user.fullName”、“user.username”和“group.name”不不存在,因此不匹配。

In order to filter these fields on the database server, you would need to use aggregate with separate $lookup stages to retrieve the user and group documents in order for the server to consider those fields.为了在数据库服务器上过滤这些字段,您需要使用aggregate和单独的$lookup阶段来检索用户和组文档,以便服务器考虑这些字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM