base_model.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. * @param {String} indexBy
  45. * @return {Promise}
  46. */
  47. async findDataByCondition(condition, fields = null, singleData = true, indexBy = null) {
  48. let result = [];
  49. if (Object.keys(condition).length <= 0) {
  50. return result;
  51. }
  52. result = singleData ? await this.db.findOne(condition, fields) : await this.db.find(condition, fields);
  53. if (indexBy !== null && !singleData && result.length > 0) {
  54. let tmpResult = {};
  55. for(let tmp of result) {
  56. tmpResult[tmp[indexBy]] = tmp;
  57. }
  58. result = tmpResult;
  59. }
  60. return result;
  61. }
  62. /**
  63. * 根据条件返回数据数量
  64. *
  65. * @param {object} condition
  66. * @return {Promise}
  67. */
  68. async count(condition = null) {
  69. let total = 0;
  70. try {
  71. total = await this.db.count(condition);
  72. } catch (error) {
  73. total = 0;
  74. }
  75. return total;
  76. }
  77. /**
  78. * 根据id删除
  79. *
  80. * @param {Number} id
  81. * @return {Promise}
  82. */
  83. async deleteById(id) {
  84. let result = false;
  85. id = parseInt(id);
  86. if (isNaN(id) || id <= 0) {
  87. return false;
  88. }
  89. try {
  90. let deleteResult = await this.db.delete({id: id});
  91. result = deleteResult.result.ok === 1;
  92. } catch (error) {
  93. console.log(error);
  94. result = false;
  95. }
  96. return result;
  97. }
  98. /**
  99. * 更新数据
  100. *
  101. * @param {Number} id
  102. * @param {Object} updateData
  103. * @return {Promise}
  104. */
  105. async updateById(id, updateData) {
  106. id = parseInt(id);
  107. if (isNaN(id) || id <= 0 || Object.keys(updateData).length <= 0) {
  108. return false;
  109. }
  110. let result = await this.db.update({id: id}, updateData);
  111. return result.ok !== undefined && result.ok === 1;
  112. }
  113. }
  114. export default BaseModel;