Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
user.save() doesn't seem to save a specific field that I add to user

If I use await user.save() in the code below it seems to get stuck but if I use it without await it seems to move ahead and in the response the passwordResetToken is displayed.. However in the database, for some reason, the rest of the fields get saved but passwordResetToken just doesn't get saved.

I am completely lost about what the reason could be.. Any direction on what I should look for would help.

exports.forgotPassword = async function(req, res, next) {

  // 1. Get user based on POST email
  const user = await User.findOne({ email: req.body.email });

  // 2. Generate random token
  user.passwordResetToken = "123456";

  await user.save({ validateBeforeSave: false });

  // 3. Send it back as an email

  //4. Send Response
  res.status(200).json({
    status: "success",
    data: {
      user: user,
    },
  });
};

this is the response


{
    "status": "success",
    "data": {
        "user": {
            "role": "user",
            "_id": "6116aeb70aae0f7c7d8800bc",
            "name": "Jane Doe",
            "email": "jane@doe.com",
            "__v": 0,
            "passwordResetToken": "123456"
        }
    }
}

However the passwordResetToken still doesn't save it to the database although the rest of it does.. I do have the passwordResetToken as a field in the mongoose.Schema

I had not added this section below to my question earlier so I am adding this to help understand where the issue might lie..

This is the userModels.js

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Name is required"],
  },
  email: {
    type: String,
    required: [true, "Email is required"],
    validate: [validator.isEmail, "Please provide valid email"],
    unique: true,
  },
  role: {
    type: String,
    enum: ["admin", "lead-guide", "guide", "user"],
    default: "user",
  },
  photo: String,
  password: {
    type: String,
    minlength: 8,
    required: [true, "Password is required"],
    select: false,
  },
  passwordConfirm: {
    type: String,
    validate: {
      validator: function(el) {
        return el === this.password;
      },
      message:
        "Password confirmation does not match with Password. Please try again",
    },
  },
  passwordChangedAt: Date,
  passwordResetToken: String,
  passwordResetExpires: Date,
});

and here's the line from userRouter.js for this route..

router.route("/forgotPassword").post(authController.forgotPassword);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Maybe you can try with

let user = await User.findOne({ email: req.body.email });

  // 2. Generate random token
  user.passwordResetToken = "123456";

  user = await user.save();

or you can use

const user = await User.findOneAndUpdate({email:req.body.email},{$set:{passwordResetToken:'123456'},{new:true})

new: true will return updated data.

about 4 years ago · Juan Pablo Isaza Relatório

0

Make sure that the model file contains the passwordResetToken field. Otherwise, it will be ignored.

about 4 years ago · Juan Pablo Isaza Relatório

0

I wonder if the issue is with the HTTP request, you might want to have http.post not http.put request for your posted question.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda