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

时间:2021-03-17 21:35:26

标签: node.js mongodb mongoose mongoose-populate

这是我的架构:

发布:

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"}]

1 个答案:

答案 0 :(得分:0)

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

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