Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!