@francesco_ksh/app-ksh-mgd-schemas 1.6.2 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/models/Order.js +37 -0
- package/package.json +1 -1
package/models/Order.js
CHANGED
|
@@ -7,6 +7,12 @@ const orderSchema = new Schema(
|
|
|
7
7
|
type: Schema.Types.ObjectId,
|
|
8
8
|
ref: 'User',
|
|
9
9
|
},
|
|
10
|
+
kashewId: {
|
|
11
|
+
type: String,
|
|
12
|
+
unique: true,
|
|
13
|
+
required: true,
|
|
14
|
+
sparse: true,
|
|
15
|
+
},
|
|
10
16
|
seller: {
|
|
11
17
|
type: Schema.Types.ObjectId,
|
|
12
18
|
ref: 'User',
|
|
@@ -507,6 +513,37 @@ const orderSchema = new Schema(
|
|
|
507
513
|
{ supressReservedKeysWarning: true }
|
|
508
514
|
);
|
|
509
515
|
|
|
516
|
+
// Pre-save hook to generate kashewId
|
|
517
|
+
orderSchema.pre('save', async function (next) {
|
|
518
|
+
const order = this;
|
|
519
|
+
|
|
520
|
+
// Only generate `kashewId` if it doesn't already exist
|
|
521
|
+
if (!order.kashewId) {
|
|
522
|
+
try {
|
|
523
|
+
// Find the highest existing kashewId and increment it
|
|
524
|
+
const lastOrder = await mongoose
|
|
525
|
+
.model('Order')
|
|
526
|
+
.findOne({})
|
|
527
|
+
.sort({ kashewId: -1 })
|
|
528
|
+
.exec();
|
|
529
|
+
|
|
530
|
+
let newId = 1; // Start from 1 if no orders exist
|
|
531
|
+
if (lastOrder && lastOrder.kashewId) {
|
|
532
|
+
const lastIdNumber = parseInt(lastOrder.kashewId.slice(3), 10); // Remove "KSH" and parse the digits
|
|
533
|
+
newId = lastIdNumber + 1;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// Format the newId as KSH followed by 5 digits
|
|
537
|
+
order.kashewId = `KSH${String(newId).padStart(5, '0')}`;
|
|
538
|
+
next();
|
|
539
|
+
} catch (err) {
|
|
540
|
+
return next(err);
|
|
541
|
+
}
|
|
542
|
+
} else {
|
|
543
|
+
next();
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
|
|
510
547
|
orderSchema.index({ '$**': 'text' });
|
|
511
548
|
orderSchema.index({ seller: 1 });
|
|
512
549
|
orderSchema.index({ status: 1 });
|