base_model.js 2.7 KB

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