首页 > 解决方案 > Mongoose 显示每个帖子的评论和星星(喜欢)

问题描述

我一直在制作一个社交网络应用程序。用户可以发布帖子,其他用户可以对帖子加注星标(点赞)或评论。

每个帖子都包含一系列评论和星号。每个评论和星标都包含对其帖子的引用。

我的帖子、评论和明星的模块结构是这样的

星型图

const StarSchema =  mongoose.Schema({

created_at : {
    type : Date,
    require : true
},
user : {
    type : mongoose.Schema.Types.ObjectId,
    ref  : 'User'
},
post : {
    type : mongoose.Schema.Types.ObjectId,
    ref  : 'Post'
}});

评论模式

const CommentSchema = mongoose.Schema({

post : {
    type : mongoose.Schema.Types.ObjectId,
    ref  : 'Post'
},
user : {
    type : mongoose.Schema.Types.ObjectId,
    ref  : 'User'
},

content : {
    type : String ,
    require : true
},
created_at : {
    type : Date,
    require : true
}});

后架构

const PostSchema = mongoose.Schema({

    content : {
        type : String,
        require : true
    },
    created_at : {
        type : Date,
        require : true
    },
    user : {
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'User'
    },
    word : {
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'Word'
    },
    comments : [{
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'Comment'
    }],
    stars : [{
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'Star'
    }]});

当我想使用此查询获取带有评论和星标的帖子时

    Post.find({_id : postId}).populate('user').exec(callback);

它给我带来了帖子,但它的评论和星星是空的,即使它有评论和星星

标签: node.jsexpressmongoosemongoose-schema

解决方案


推荐阅读