-
Notifications
You must be signed in to change notification settings - Fork 286
/
post.js
61 lines (58 loc) · 1.4 KB
/
post.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ObjectId } from 'mongodb';
import { dbProjectionUsers } from './user';
export async function findPostById(db, id) {
const posts = await db
.collection('posts')
.aggregate([
{ $match: { _id: new ObjectId(id) } },
{ $limit: 1 },
{
$lookup: {
from: 'users',
localField: 'creatorId',
foreignField: '_id',
as: 'creator',
},
},
{ $unwind: '$creator' },
{ $project: dbProjectionUsers('creator.') },
])
.toArray();
if (!posts[0]) return null;
return posts[0];
}
export async function findPosts(db, before, by, limit = 10) {
return db
.collection('posts')
.aggregate([
{
$match: {
...(by && { creatorId: new ObjectId(by) }),
...(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 insertPost(db, { content, creatorId }) {
const post = {
content,
creatorId,
createdAt: new Date(),
};
const { insertedId } = await db.collection('posts').insertOne(post);
post._id = insertedId;
return post;
}