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