I want to make the generation of the codigoSS before the validation but when i try the end point i recibe the message: "Solicitud validation failed: codigoSS: Path codigoSS
is required.".
Went i change the required value to false on the model i get the answer i want, but i need the value as required.
import mongoose from "mongoose";
const solicitudSchema = new mongoose.Schema(
{
fechaSolicitud: {
type: Date,
required: true,
default: Date.now
},
codigoSS: {
type: String,
unique: true,
required: true,
}
},
{
timestamps: true,
}
);
solicitudSchema.pre("save", async function (next) {
if (!this.codigoSS) {
const count = await mongoose.models.Solicitud.countDocuments();
this.codigoSS = `SS${String(count + 1).padStart(3, "0")}`;
console.log(this.codigoSS);
}
next();
});
I want to make the generation of the codigoSS before the validation but when i try the end point i recibe the message: "Solicitud validation failed: codigoSS: Path codigoSS
is required.".
Went i change the required value to false on the model i get the answer i want, but i need the value as required.
import mongoose from "mongoose";
const solicitudSchema = new mongoose.Schema(
{
fechaSolicitud: {
type: Date,
required: true,
default: Date.now
},
codigoSS: {
type: String,
unique: true,
required: true,
}
},
{
timestamps: true,
}
);
solicitudSchema.pre("save", async function (next) {
if (!this.codigoSS) {
const count = await mongoose.models.Solicitud.countDocuments();
this.codigoSS = `SS${String(count + 1).padStart(3, "0")}`;
console.log(this.codigoSS);
}
next();
});
Share
Improve this question
edited 2 days ago
Daniel A. White
191k49 gold badges379 silver badges463 bronze badges
asked 2 days ago
Giovanni PalenciaGiovanni Palencia
112 bronze badges
1 Answer
Reset to default 1The problem was the validation process of the mongoSchema, the solution is:
solicitudSchema.pre("validate", async function (next) {
if (!this.codigoSS) {
const count = await mongoose.models.Solicitud.countDocuments();
this.codigoSS = `SS${String(count + 1).padStart(3, "0")}`;
console.log(this.codigoSS);
}
next();
});