【发布时间】:2021-09-25 21:12:33
【问题描述】:
技术:MongoDB、ExpressJS
我有 3 个架构
- 用户架构:
userSchema = {
name: {type: String},
password: {type: String},
email: {type: String},
friends: {type: [mongoose.Types.ObjectId]}
}
- textPostSchema =
textPostSchema = {
text: {type: String},
postType: {type: String, default: "textPost"},
userId: {type: mongoose.Types.ObjectId}
}
- articalPostSchema:
articalPostSchema = {
title: {type: String},
content: {type: String}
postType: {type: String, default: "articalPost"},
userId: {type: mongoose.Types.ObjectId}
}
现在我有一个社交媒体应用程序,当用户的朋友帖子是帖子时,我必须在其中显示这两个帖子,并包括无限滚动。 textPost 和 articalPost 都应该发送到前端,并且一次只能发送 10 个帖子。我应该如何为时间轴编写 API?
输出应如下所示:
{
post: [
{
title: "artical Post title",
content: "artical post content",
postType: "articalPost",
userId: "60b9c9801a2a2547de643ccd"
},
{
text: "text post ",
postType: "textPost",
userId: "60b9c9801a2a2547de643ccd"
},
... 8 more
]
}
更新: 我得到了解决方案:- 我在更多架构上创建:
timelineSchema = {
postId: {
type: mongoose.Types.ObjectId,
required: true,
ref: function () {
switch (this.postCategoryType) {
case 'articleposts':
return 'ArticlePost';
case 'textposts':
return 'TextPost';
}
},
},
postCategoryType: {
type: String,
required: true,
},
userId: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'User',
},
},
然后我创建了一个函数来只获取朋友的帖子:
exports.getTimelinePosts = async (req, res) => {
try {
const timelinePosts = await TimelineModel.find({
userId: { $in: [...req.user.friends, req.params.id] },
})
.skip((req.params.page - 1) * 10)
.limit(10)
.sort({ createdAt: -1 })
.populate('postId');
return res.status(200).json({ status: 'success', data: timelinePosts });
} catch (error) {
return res.status(500).json(error);
}
};
【问题讨论】:
-
您想在一个帖子对象中合并文章帖子架构和文本帖子架构?
-
@AbuSayeedMondal 是的,您可以说,每次我调用 API 获取帖子时,API 都应该响应下一个 10 个帖子,这 10 个帖子应该属于 textPost 或 articlePost 或两者都根据@ 987654329@.
标签: javascript mongodb express mongoose mongodb-query