33 lines
703 B
JavaScript
33 lines
703 B
JavaScript
'use strict';
|
|
|
|
const { generateUniqueCode } = require('./uniqueCode');
|
|
|
|
/**
|
|
* Mongoose plugin: auto-assigns an 8-digit uniqueCode before validation if missing.
|
|
*/
|
|
const uniqueCodePlugin = (schema, options = {}) => {
|
|
const field = options.field || 'uniqueCode';
|
|
|
|
schema.add({
|
|
[field]: {
|
|
type: String,
|
|
unique: true,
|
|
sparse: true,
|
|
trim: true,
|
|
index: true
|
|
}
|
|
});
|
|
|
|
schema.pre('validate', async function assignUniqueCode(next) {
|
|
if (this[field]) return next();
|
|
try {
|
|
this[field] = await generateUniqueCode(this.constructor, field);
|
|
return next();
|
|
} catch (err) {
|
|
return next(err);
|
|
}
|
|
});
|
|
};
|
|
|
|
module.exports = uniqueCodePlugin;
|