123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- /**
- * 数据模型基类
- *
- * @author CaiAoLin
- * @date 2017/6/22
- * @version
- */
- import MongooseHelper from "../helper/mongoose_helper";
- class BaseModel {
- /**
- * mongoose数据模型
- *
- * @var {object}
- */
- model = null;
- /**
- * 构造函数
- *
- * @return {void}
- */
- constructor() {
- if (new.target === BaseModel) {
- throw new Error('BaseModel不能实例化,只能继承使用。');
- }
- }
- /**
- * 初始化函数
- *
- * @return {void}
- */
- init() {
- if (this.model === null) {
- throw new Error('子类数据有误');
- }
- this.db = new MongooseHelper();
- this.db.model = this.model;
- }
- /**
- * 根据id查找对应数据
- *
- * @param {Object} condition
- * @param {Object} fields
- * @param {boolean} singleData
- * @return {Promise}
- */
- async findDataByCondition(condition, fields = null, singleData = true) {
- if (Object.keys(condition).length <= 0) {
- return null;
- }
- let data = await singleData ? this.db.findOne(condition, fields) : this.db.find(condition);
- return data;
- }
- /**
- * 根据条件返回数据数量
- *
- * @param {object} condition
- * @return {Promise}
- */
- async count(condition = null) {
- let total = 0;
- try {
- total = await this.db.count(condition);
- } catch (error) {
- total = 0;
- }
- return total;
- }
- /**
- * 根据id删除
- *
- * @param {Number} id
- * @return {Promise}
- */
- async deleteById(id) {
- let result = false;
- id = parseInt(id);
- if (isNaN(id) || id <= 0) {
- return false;
- }
- try {
- let deleteResult = await this.db.delete({id: id});
- result = deleteResult.result.ok === 1;
- } catch (error) {
- console.log(error);
- result = false;
- }
- return result;
- }
- }
- export default BaseModel;
|