ensl_gathers/db/models/message.js

49 lines
1.1 KiB
JavaScript
Raw Normal View History

2015-08-05 00:41:43 +00:00
"use strict";
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var messageSchema = new Schema({
author: {
username: { type: String, required: true },
avatar: String
},
content: { type: String, required: true },
2015-08-07 00:47:23 +00:00
createdAt: { type: Date, default: Date.now, required: true },
deleted: { type: Boolean, default: false }
2015-08-05 00:41:43 +00:00
});
2015-08-07 00:47:23 +00:00
messageSchema.index({ createdAt: -1 });
messageSchema.index({ deleted: 1, createdAt: -1 });
2015-12-28 13:21:35 +00:00
messageSchema.index({ content: "text", "author.username": "text" });
2015-08-05 00:41:43 +00:00
2015-09-25 21:23:30 +00:00
messageSchema.methods.toJson = function () {
2015-08-05 00:41:43 +00:00
return {
id: this.id,
author: this.author,
content: this.content,
createdAt: this.createdAt
};
};
2015-09-25 21:23:30 +00:00
messageSchema.statics.list = function (options, callback) {
let query = this.find({deleted: false})
if (options.before) {
query.where({
createdAt: {
$lt: new Date(options.before)
}
});
}
return query.sort({createdAt: -1})
2015-08-10 23:56:53 +00:00
.limit(30)
.exec((error, messages) => {
if (error) return callback(error);
return callback(null, messages.reverse());
});
2015-08-07 00:06:40 +00:00
};
2015-08-18 09:56:35 +00:00
module.exports = mongoose.model('Message', messageSchema);