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

47 lines
1009 B
JavaScript

const mongoose = require('../db/connect')
const { Schema } = mongoose
const crmCompany = new Schema({
companyId: {
type: String,
required: true,
},
name: {
type: String
}
}, {
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 () {
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