javascript - 如何编写猫鼬查询来组合来自两个模型的数据?
问题描述
技术: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);
}
};
解决方案
假设您使用的是 express 和 mongoose。获取两者的代码,
// first bring all those schema from your mongoose models
const Article = require('./models/ArticleSchema');
const Text = require('./models/TextSchema');
const fetchArticleAndTextPost = async (req, res)=>{
//find all data
const articles = await Article.find();
const texts = await Text.find();
//join them together
const post = articles.concat(texts);
return res.status(200).json({
status: 200,
data: post,
})
}
推荐阅读
- c++ - 数字序列的最佳数据结构 [0:9]
- java - 如何针对 Avro 架构验证 JSON
- python - Python替换文本
- c++ - 可以在 C++ QObject::connect() 中连接 QML 对象现有信号吗?
- java - [JAVA]递归删除扫雷中的空单元格
- javascript - material-ui-next 的组件 Modal 没有被 Babel 转换为 ES5
- listview - 如何更改 TListGroups 中的组顺序?
- java - 使用 UWC java regex 将 Mediawiki 迁移到 Confluence 无法与在线 |thumb 匹配
- android - 工具栏子节点不居中
- javascript - 使用Jquery或JS在html表中查找列的总和