-
Notifications
You must be signed in to change notification settings - Fork 286
/
comment.js
40 lines (38 loc) · 984 Bytes
/
comment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { ObjectId } from 'mongodb';
import { dbProjectionUsers } from '.';
export async function findComments(db, postId, before, limit = 10) {
return db
.collection('comments')
.aggregate([
{
$match: {
postId: new ObjectId(postId),
...(before && { createdAt: { $lt: before } }),
},
},
{ $sort: { _id: -1 } },
{ $limit: limit },
{
$lookup: {
from: 'users',
localField: 'creatorId',
foreignField: '_id',
as: 'creator',
},
},
{ $unwind: '$creator' },
{ $project: dbProjectionUsers('creator.') },
])
.toArray();
}
export async function insertComment(db, postId, { content, creatorId }) {
const comment = {
content,
postId: new ObjectId(postId),
creatorId,
createdAt: new Date(),
};
const { insertedId } = await db.collection('comments').insertOne(comment);
comment._id = insertedId;
return comment;
}