【发布时间】: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