base_model.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * 数据模型基类
  3. *
  4. * @author CaiAoLin
  5. * @date 2017/6/22
  6. * @version
  7. */
  8. import MongooseHelper from "../helper/mongoose_helper";
  9. class BaseModel {
  10. /**
  11. * mongoose数据模型
  12. *
  13. * @var {object}
  14. */
  15. model = null;
  16. /**
  17. * 构造函数
  18. *
  19. * @return {void}
  20. */
  21. constructor() {
  22. if (new.target === BaseModel) {
  23. throw new Error('BaseModel不能实例化,只能继承使用。');
  24. }
  25. }
  26. /**
  27. * 初始化函数
  28. *
  29. * @return {void}
  30. */
  31. init() {
  32. if (this.model === null) {
  33. throw new Error('子类数据有误');
  34. }
  35. this.db = new MongooseHelper();
  36. this.db.model = this.model;
  37. }
  38. /**
  39. * 根据id查找对应数据
  40. *
  41. * @param {Object} condition
  42. * @param {Object} fields
  43. * @param {boolean} singleData
  44. * @return {Promise}
  45. */
  46. async findDataByCondition(condition, fields = null, singleData = true) {
  47. if (Object.keys(condition).length <= 0) {
  48. return null;
  49. }
  50. let data = await singleData ? this.db.findOne(condition, fields) : this.db.find(condition);
  51. return data;
  52. }
  53. /**
  54. * 根据条件返回数据数量
  55. *
  56. * @param {object} condition
  57. * @return {Promise}
  58. */
  59. async count(condition = null) {
  60. let total = 0;
  61. try {
  62. total = await this.db.count(condition);
  63. } catch (error) {
  64. total = 0;
  65. }
  66. return total;
  67. }
  68. /**
  69. * 根据id删除
  70. *
  71. * @param {Number} id
  72. * @return {Promise}
  73. */
  74. async deleteById(id) {
  75. let result = false;
  76. id = parseInt(id);
  77. if (isNaN(id) || id <= 0) {
  78. return false;
  79. }
  80. try {
  81. let deleteResult = await this.db.delete({id: id});
  82. result = deleteResult.result.ok === 1;
  83. } catch (error) {
  84. console.log(error);
  85. result = false;
  86. }
  87. return result;
  88. }
  89. }
  90. export default BaseModel;