mongodb - MongoDB 基于参考 id 加入用户和点赞集合
问题描述
我正在尝试使用 ExpressJS 和 MongoDB 创建一个小型社交网络。我有一个关于喜欢和帖子收集的小问题。我知道您可以将 a 嵌入到likes
集合posts
中,但我决定将这两个集合分开并使用参考 ID,以便稍后加入它们。我目前遇到的主要问题是,如何在集合中包含likes
参考?posts
假设我的posts
架构看起来像这样:
const PostSchema = new Schema({
content: { type: String, required: true },
isLiked: false,
}, { timestamps: true });
我的likes
架构看起来像这样:
const LikeSchema = new Schema(
{
// The user who is liking the post.
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
// The post that is being liked.
question: {
type: Schema.Types.ObjectId,
ref: 'Question',
required: true
},
},
{ timestamps: true }
);
我想这样做,以便每当我尝试查询帖子集合时,我也可以通过引用集合而不修改嵌入其中的模式来获得嵌入其中的喜欢likes
。
示例响应:
{
_id: ObjectId("test"),
content: 'A post',
isLiked: false,
likes: ["A user object here based on the `likes collection`"]
}
解决方案
您必须在发送响应之前获取它们:
- 找到所有喜欢的帖子,类似于
Like.find({ question: <postId> })
- 然后您可以解决喜欢的用户,在上面的命令中您可以
.populate('user')
与猫鼬填充功能连接 - 如果您只对用户对象而不是整个类似对象感兴趣,则可以提取已解析的用户:
const users = likes.map(x => x.user)
- 然后您可以将 users 数组添加到 post 对象并将最终对象作为响应发送
推荐阅读
- reactjs - 为什么我的请求在解决后仍处于待处理状态?
- postgresql - Npgsql.NpgsqlException(0x80004005):连接时出现异常:由于目标机器主动拒绝,无法建立连接
- google-calendar-api - 如何更新具有某些豁免的重复事件,但仍保持豁免实例的“已确认”状态?
- image - SwiftUI - 如何使来自不同大小的 URL 的图像适合框架?
- wpf - WPF:绑定到 ObservableCollection 中类的属性
- global-variables - 当“on_test_start”存在时,蝗虫任务方法无法获取全局值
- sql - 不使用 'INTERSECT' ,如何只检索两个表中存在的行?
- php - 在同一行的 PHP PDO 中不断给出 $_GET 错误
- string - 如何在 SwiftUI 中将字符串转换为整数?
- c++ - Qt中如何将非成员函数中的数据导入到成员函数中?