【问题标题】:mongoose fetch posts by user and by his followings猫鼬按用户和他的追随者获取帖子
【发布时间】:2019-02-02 02:26:56
【问题描述】:

如何获取用户的帖子及其所有关注的帖子(Mongodb、Mongoose、Nodejs)

用户架构

const userSchema = new mongoose.Schema({
    firstName: { type: String, required: true, trim: true },
    lastName: { type: String, required: true, trim: true },
});
userSchema.set('timestamps', true);

export default mongoose.model('user', userSchema);

追随者架构

const followSchema = new mongoose.Schema({
    follower: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    following: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    status: { type: Boolean, default: true }
});
followSchema.set('timestamps', true);

export default mongoose.model('follow', followSchema);

帖子架构

const postSchema = new mongoose.Schema({
    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    contents: { type: String, trim: true },
    photo: { type: String }
});
postSchema.set('timestamps', true);

export default mongoose.model('post', postSchema);

提前感谢您! :)

【问题讨论】:

  • 不清楚你在问什么。试着解释一下
  • @AnthonyWinzlet 让我举个例子来解释一下,假设我们有 3 个用户 A、B 和 C,A 都关注 B 和 C,现在我想从帖子集合中获取所有帖子,但帖子由A 和 B & C,因为 A 跟随 B & C。让我知道。如果它再次不清楚。
  • 好的,所以您想获取所有由用户 A 或其追随者创建的帖子?你是什​​么mongodb版本?你能发布一些示例数据吗
  • @AnthonyWinzlet 是的! mongodb版本---MongoDB版本v4.0.5。您需要什么样本数据,请解释一下?只是跟随模式包含两个用户ID,我的意思是用户自己是跟随者,另一个是跟随者。
  • @spyro 我已经在阅读文档,但尚未找到解决方案,但仍然继续感谢您的帮助!

标签: node.js mongodb mongoose


【解决方案1】:

Hy Alamghir 很高兴在这里见到您,很抱歉您仍然没有得到答案,在看到您的架构后我可以建议您,我认为无需创建三个集合,您只需要 2 个架构第一个

const userSchema = new mongoose.Schema({
  firstName: { type: String, required: true, trim: true },
  lastName: { type: String, required: true, trim: true },
  followers:[]
});
userSchema.set('timestamps', true);

export default mongoose.model('user', userSchema);

现在在关注者数组中只需推送关注此用户的用户的 ID 现在您可以很容易地让这些人完成这样的帖子让假设您在 userData 变量中有用户数据现在您可以这样做

db.postSchema.find($or:[{userId:userData._id},{userId:$in:userData.followers}])

【讨论】:

  • 感谢您的回答。试图得到你的建议,如果它对我有帮助,我会告诉你:)
  • 当心。我也是这么想的,但你(@mzparacha)写的是一个 mongodb-antipattern。追随者数组将超出界限,并将达到 mongodb (16 MB) 中的文档大小限制。因此,您至少可以在该数组中存储大约 1.300.000 个跟随者对象 ID,但随后会达到限制。既然我们谈论的是“追随者”,100 万似乎不是一个巨大的数字:/
  • 谢谢@spyro,你说得对,我不认为它会影响未来的应用程序我认为 Alamghir 你做得对,如果它没有帮助就使用填充让我知道我会建议你还有其他解决方案
  • @mzparacha 你通常不会想到这些场景,除非你正在处理这样的休克数字。由于我在工作中与休数字打交道,因此这种意识一直存在于我的脑海中^^
【解决方案2】:

抱歉,你的问题搞错了。

可能有更好的解决方案,但您应该能够这样做:

(这会获取关注您的原始用户的人的帖子。如果您确实是相反的意思,只需切换 :))

// get the user's posts:
var theUserPosts = await postSchema.find({userId: userData._id}).exec();

// get the follower-IDs:
var theFollowersIDs = await followSchema.find({follower: userData._id, status: true}, 'following').exec();

// get the posts of those followers:
var followerPosts = await postSchema.find({userId: {$in: theFollowersIDs}}).exec();

你能试试这个并告诉我们这是否适合你吗?

【讨论】:

  • 好的,我正在考虑您的答案,如果这有帮助,我会通知您。再次感谢:)
猜你喜欢
  • 2020-06-30
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-13
  • 2013-09-15
  • 2013-09-28
相关资源
最近更新 更多