猫鼬 |按填充项数组中的字段数组搜索

问题描述

这是我的架构:

发布:

const postSchema = mongoose.Schema({
   ...
   tags: [{
        type: mongoose.Schema.Types.ObjectId,ref: "Tag"
   }]
   ...
})

标签

const tagSchema = mongoose.Schema({
    name: String
});

问题

有没有办法用标签名称数组提供 Post 模型并找到包含这些标签的帖子?

类似于:

exports.getPostsByTags = (req,res,next) => {
    var tags = JSON.parse(req.params.tags);
    //HOW TO USE Post.find({.....}) So i can retrieve posts which contains var tags array
    Post.find({.....}).populate("tags")
        .then(documents => {
            fetchedPosts = documents;
            res.status(200).json({
                message: "Posts by Tags fetched succesfully!",posts: fetchedPosts,});
        })
        .catch(error => {
            res.status(500).json({
                message: "Fetching posts by Tags Failed"
            })
        });
}

示例路由调用

http://localhost:3000/api/posts/tags/[{"name": "d2"},{"name": "d1"}]

解决方法

documentation 中所述,您可以将 match 对象传递给 populate 调用,您可以在其中执行以下操作:

const tags = JSON.parse(req.params.tags).map(tag => tag.name);
Post.find({}).populate({
            path: 'tags',match: {
                name: {$in: tags}
            }
        });