-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.js
48 lines (42 loc) · 1.75 KB
/
mongo.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
const config = require('config-lite')(__dirname)
const Mongolass = require('mongolass')
const mongolass = new Mongolass()
const moment = require('moment')
const objectIdToTimestamp = require('objectid-to-timestamp')
mongolass.connect(config.mongodb)
exports.User = mongolass.model('User', {
name: { type: 'string', required: true },
password: { type: 'string', required: true },
avatar: { type: 'string', required: true },
gender: { type: 'string', enum: ['m', 'f', 'x'], default: 'x' },
bio: { type: 'string', required: true }
})
exports.User.index({ name: 1 }, { unique: true }).exec()// 根据用户名找到用户,用户名全局唯一
// 根据 id 生成创建时间 created_at
mongolass.plugin('addCreatedAt', {
afterFind: function (results) {
results.forEach(function (item) {
item.created_at = moment(objectIdToTimestamp(item._id)).format('YYYY-MM-DD HH:mm')
})
return results
},
afterFindOne: function (result) {
if (result) {
result.created_at = moment(objectIdToTimestamp(result._id)).format('YYYY-MM-DD HH:mm')
}
return result
}
})
exports.Post = mongolass.model('Post', {
author: { type: Mongolass.Types.ObjectId, required: true },
title: { type: 'string', required: true },
content: { type: 'string', required: true },
pv: { type: 'number', default: 0 }
})
exports.Post.index({ author: 1, _id: -1 }).exec()// 按创建时间降序查看用户的文章列表
exports.Comment = mongolass.model('Comment', {
author: { type: Mongolass.Types.ObjectId, required: true },
content: { type: 'string', required: true },
postId: { type: Mongolass.Types.ObjectId, required: true }
})
exports.Comment.index({ postId: 1, _id: 1 }).exec()// 通过文章 id 获取该文章下所有留言,按留言创建时间升序