【问题标题】:mongoose | search by array of fields in array of populated items猫鼬 |按填充项目数组中的字段数组搜索
【发布时间】:2021-06-15 07:02:02
【问题描述】:

这是我的架构:

帖子:

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

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

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

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

    【讨论】:

    • 它正在工作!唯一的问题是它返回带有空标签的帖子。
    • 其实不行,它会返回所有的帖子,但会删除标签数组中没有的标签
    • 我通过迭代结果并检查 post.tags.length>0 来实现它。如果有更优化的方法,请告诉我 :) 感谢您的努力!
    猜你喜欢
    • 1970-01-01
    • 2019-04-06
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多