crm-api-template-generator/backend/models/Company.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-11-29 20:05:48 +00:00
const mongoose = require('../db/connect')
const { Schema } = mongoose
const crmCompany = new Schema({
companyId: {
type: String,
required: true,
},
name: {
type: String
},
integrations: [
{
name: { type: String, required: true },
config: {
type: Schema.Types.Mixed,
default: {}
}
}
]
2023-11-29 20:05:48 +00:00
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
})
crmCompany.virtual('crms', {
ref: 'CRM',
localField: '_id',
foreignField: 'company',
justOne: false,
// match: { rating: 4 }
})
crmCompany.pre('deleteOne', { document: true, query: false }, async function () {
2023-11-29 20:05:48 +00:00
const crms = await this.model('CRM').find({ company: this._id })
for (const crm of crms) {
await crm.deleteOne() // Delete each CRM
// Delete associated CRM_Contacts
const crmContacts = await this.model('CRM_Contact').find({ crm: crm._id })
for (const crmContact of crmContacts) {
await crmContact.deleteOne()
}
}
}
)
const Company = mongoose.model('Company', crmCompany)
module.exports = Company