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

104
Visualizações
findOneReplace replacment issue

I want to find a document in my db and replace it with a document that has a new name and new key.

Here is my Schema

const Schema = mongoose.Schema;

const vampireSchema = new Schema({
  name: { type: String, required: true },
  title: String,
  hair_color: {type: String, default: "blonde" },
  eye_color: String,
  dob: Date,
  loves: [String],
  location: String,
  gender: String,
  victims: {type: Number, min: 0}

});

const Vampire = mongoose.model("Vampire", vampireSchema);

module.exports = Vampire;

Here is my executable code

Vampire.findOneAndReplace( { name: "Claudia" }, { name: "Eve", portrayed_by: "Tilda Swinton" }, (err, vamp) => {
  if(err){
    console.log(err)
  }
  else{
    console.log(vamp)
  }
  db.close()
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are two issues that I can see.

First, you should pass null as the third argument in your findOneAndReplace call. This will set the options to null and should get your code running. This is in my opinion a strange behavior of mongoose.

Vampire.findOneAndReplace( 
        { name: "Claudia" }, 
        { name: "Eve", portrayed_by: "Tilda Swinton" }, 
        null, 
        (err, vamp) => 
{
  if(err){
    console.log(err)
  }
  else{
    console.log(vamp)
  }
  db.close()
})

Secondly, I would recommend adding the portrayed_by to the schema, otherwise, that field will not be in the newly created document. Therefore, I would adjust your schema that way:

const vampireSchema = new Schema({
  name: { type: String, required: true },
  title: String,
  hair_color: {type: String, default: "blonde" },
  eye_color: String,
  dob: Date,
  loves: [String],
  location: String,
  gender: String,
  victims: {type: Number, min: 0},
  portrayed_by: String
});
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