最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to add a required value with a middleware? - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 1

The 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();
});

发布评论

评论列表(0)

  1. 暂无评论