show comments like facebook with express

穿精又带淫゛_ 提交于 2020-01-06 08:51:03

问题


I have the next Schema:

var eventSchema = mongoose.Schema({
    title: 'string',
    propietary_id: 'String',
    comments : [{
        text: 'string',
        user: { type : mongoose.Schema.Types.ObjectId, ref : 'users' },
        createdAt: {type: Date, default: Date.now }  
    }]
});

my query:

Event.find().populate('comments.user').exec(function(err, doc){
   console.log(err);
   console.log(doc);
});

it's possible return object with events information, 2 comments and total number of comments (like facebook) ?


回答1:


I would do it like this:

var NBR_OF_COMMENTS = 2;
Event.find().populate('comments.user').exec(function(err, event){
    var comments = event.comments;
    var totalNbrOfComments = comments.length;
    comments.splice(NBR_OF_COMMENTS, totalNbrOfComments - NBR_OF_COMMENTS);
    event.comments = {
        count: comments.length,
        total: totalNbrOfComments,
        items: comments,
    };
    res.json(event);
});

For example, this should return the following:

{
    title: 'test',
    property_id: '123',
    comments: {
        count: 2,
        total: 5,
        items: [
            {
                text: 'comment 1',
                ...
            },
            {
                text: 'comment 2',
                ...
            },
        ],
    }
}


来源:https://stackoverflow.com/questions/25836360/show-comments-like-facebook-with-express

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!