Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用express显示类似facebook的评论_Express - Fatal编程技术网

使用express显示类似facebook的评论

使用express显示类似facebook的评论,express,Express,我有下一个模式: var eventSchema = mongoose.Schema({ title: 'string', propietary_id: 'String', comments : [{ text: 'string', user: { type : mongoose.Schema.Types.ObjectId, ref : 'users' }, createdAt: {type: Date, default:

我有下一个模式:

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 }  
    }]
});
我的问题是:

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

有可能返回包含事件信息、2条评论和评论总数的对象(如facebook)?

我会这样做:

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);
});
例如,这应返回以下内容:

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