2022-08-29 19:31:59 +03:00
|
|
|
const mongoose = require("mongoose");
|
|
|
|
const UserModel = require("./User");
|
|
|
|
const MessageModel = require("./Message");
|
2022-08-09 19:16:34 +03:00
|
|
|
const schema = new mongoose.Schema({
|
|
|
|
id: { type: String, unique: true },
|
2022-04-06 21:14:46 +03:00
|
|
|
|
2022-08-09 19:16:34 +03:00
|
|
|
author: UserModel.schema,
|
2022-04-06 21:14:46 +03:00
|
|
|
|
|
|
|
title: String,
|
2022-08-09 19:16:34 +03:00
|
|
|
time: { type: Date, default: Date.now },
|
2022-04-06 21:14:46 +03:00
|
|
|
deleted: { type: Boolean, default: false },
|
2022-08-29 19:31:59 +03:00
|
|
|
edited: { type: Boolean, default: false },
|
|
|
|
|
2022-08-28 15:00:53 +03:00
|
|
|
messages: [String],
|
|
|
|
views: { type: Number, default: 0 }
|
2022-08-09 19:16:34 +03:00
|
|
|
|
|
|
|
});
|
|
|
|
|
2022-08-29 19:31:59 +03:00
|
|
|
schema.virtual('authorID').get(function () { return this.author?.id; });
|
|
|
|
schema.methods.messageCount = async function (admin = false) {
|
|
|
|
const query = { threadID: this.id };
|
|
|
|
if (!admin) query.deleted = false;
|
|
|
|
return await MessageModel.count(query) || 0;
|
|
|
|
};
|
2022-08-09 19:16:34 +03:00
|
|
|
schema.methods.push = function (messageID) {
|
|
|
|
this.messages.push(messageID);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
schema.methods.takeId = async function () {
|
|
|
|
this.id = await model.count() || 0;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
schema.methods.getLink = function (id = this.id) {
|
|
|
|
return "/threads/" + id;
|
|
|
|
}
|
|
|
|
|
|
|
|
const model = mongoose.model('thread', schema);
|
|
|
|
|
|
|
|
model.get = id => model.findOne({ id });
|
2022-04-06 21:14:46 +03:00
|
|
|
|
2022-08-09 19:16:34 +03:00
|
|
|
module.exports = model;
|