const mongoose = require('mongoose'); const Schema = mongoose.Schema; const tools = require('../tools/general'); const { ObjectID } = require('mongodb'); mongoose.Promise = global.Promise; mongoose.level = "F"; // Resolving error Unknown modifier: $pushAll mongoose.plugin(schema => { schema.options.usePushEach = true }); const SettingsSchema = new Schema({ idapp: { type: String, }, key: { type: String, }, type: { type: Number, }, value_str: { type: String, }, value_date: { type: Date, }, value_num: { type: Number, }, value_bool: { type: Boolean, }, serv: { type: Boolean, default: false } }); SettingsSchema.statics.getFieldsForSearch = function () { return ['key', 'value_str'] }; SettingsSchema.statics.executeQueryTable = function (idapp, params) { params.fieldsearch = this.getFieldsForSearch(); return tools.executeQueryTable(this, idapp, params); }; SettingsSchema.statics.getValDbSettings = function (idapp, key, def) { return Settings.findOne({ idapp, key }) .then((myrec) => { // console.log('getValDbSettings', myrec, 'idapp', idapp); if (myrec) { if (myrec.type === tools.FieldType.date) return myrec.value_date; else if (myrec.type === tools.FieldType.number) return myrec.value_num; else if (myrec.type === tools.FieldType.boolean) return myrec.value_bool; else return myrec.value_str; } else { return def } }).catch((err) => { console.error('getValDbSettings', err); return def; }); }; SettingsSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) { return tools.DuplicateAllRecords(this, idapporig, idappdest); }; SettingsSchema.statics.findAllIdApp = function (idapp, serv) { const Settings = this; let myfind = ''; if (serv) myfind = { idapp, serv }; else myfind = { idapp }; return Settings.find(myfind, (err, arrrec) => { return arrrec }); }; SettingsSchema.statics.setKeyNum = async function (idapp, key, value) { const Settings = this; let myrec = await Settings.findOne({ idapp, key }); if (!myrec) { myrec = new Settings({ key }); myrec._id = new ObjectID(); myrec.idapp = idapp; myrec.type = tools.FieldType.number; myrec.value_num = value; return await myrec.save(); } else { myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_num: value } }, { new: false}); } }; SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) { const Settings = this; const ret = await Settings.findOne({ idapp, key}); if (!!ret) { return ret.value_num; } else { return mydefault; } }; const Settings = mongoose.model('Settings', SettingsSchema); module.exports = { Settings };