猫鼬按用户及其关注者获取帖子

时间:2019-02-01 15:26:18

标签: node.js mongodb mongoose

如何按用户及其以下所有帖子(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);

先谢谢您! :)

2 个答案:

答案 0 :(得分:0)

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);

现在在followers数组中只需推送关注该用户的用户的ID现在,您将很容易获得像这样的人完成的帖子,假设您现在在userData变量中拥有用户数据,您可以做这个

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

答案 1 :(得分:-1)

对不起,你的问题错了。

也许有更好的解决方案,但是您应该能够做到这一点:

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

// 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();

你可以试试这个,如果这个作品告诉我们的吗?