Spaces:
Runtime error
Runtime error
File size: 3,118 Bytes
56b6519 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ClientSchema = new Schema(
{
email: { type: String, required: true, unique: true },
company: { type: Schema.Types.ObjectId, ref: 'Company' },
lastname: String,
firstname: String,
phone: String,
cell: String,
title: String,
},
{ timestamps: true },
);
/*
*** Statics ***
*/
// Get all clients
ClientSchema.statics.getAll = () => {
return new Promise((resolve, reject) => {
var query = Client.find().populate('company', '-_id name');
query.select('email lastname firstname phone cell title');
query
.exec()
.then(rows => {
resolve(rows);
})
.catch(err => {
reject(err);
});
});
};
// Create client
ClientSchema.statics.create = (client, company) => {
return new Promise(async (resolve, reject) => {
if (company) {
var Company = mongoose.model('Company');
var query = Company.findOneAndUpdate(
{ name: company },
{},
{ upsert: true, new: true },
);
var companyRow = await query.exec();
if (companyRow) client.company = companyRow._id;
}
var query = new Client(client);
query
.save(company)
.then(row => {
resolve({
_id: row._id,
email: row.email,
firstname: row.firstname,
lastname: row.lastname,
title: row.title,
phone: row.phone,
cell: row.cell,
company: row.company,
});
})
.catch(err => {
if (err.code === 11000)
reject({
fn: 'BadParameters',
message: 'Client email already exists',
});
else reject(err);
});
});
};
// Update client
ClientSchema.statics.update = (clientId, client, company) => {
return new Promise(async (resolve, reject) => {
if (company) {
var Company = mongoose.model('Company');
var query = Company.findOneAndUpdate(
{ name: company },
{},
{ upsert: true, new: true },
);
var companyRow = await query.exec();
if (companyRow) client.company = companyRow.id;
}
var query = Client.findOneAndUpdate({ _id: clientId }, client);
query
.exec()
.then(rows => {
if (rows) resolve(rows);
else reject({ fn: 'NotFound', message: 'Client Id not found' });
})
.catch(err => {
if (err.code === 11000)
reject({
fn: 'BadParameters',
message: 'Client email already exists',
});
else reject(err);
});
});
};
// Delete client
ClientSchema.statics.delete = clientId => {
return new Promise((resolve, reject) => {
var query = Client.findOneAndDelete({ _id: clientId });
query
.exec()
.then(rows => {
if (rows) resolve(rows);
else reject({ fn: 'NotFound', message: 'Client Id not found' });
})
.catch(err => {
reject(err);
});
});
};
/*
*** Methods ***
*/
var Client = mongoose.model('Client', ClientSchema);
module.exports = Client;
|