【问题标题】:show comments like facebook with express用 express 显示像 facebook 这样的评论
【发布时间】:2014-11-08 06:57:24
【问题描述】:

我有下一个架构:

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 个 cmets 和 cmets 总数(如 facebook)的对象吗?

【问题讨论】:

    标签: express


    【解决方案1】:

    我会这样做:

    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',
                    ...
                },
            ],
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-23
      • 2012-10-14
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多