Search code examples
node.jsmongoosehandlebars.js

Error "DocumentNotFoundError: No document found for query "{ _id:xxx}


I cloned the object "preventivo", when I run this code I have the following error: (node:24548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DocumentNotFoundError: No document found for query "{ _id: 5ff6110e27bbf25fe45ce2b5 }" on model "preventivi" i can't understand the error, can you help me? i use node + mongoose + handlebars thanks

//ROUTE CLONA PREVENTIVO
app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
    Preventivi.findOne({
      _id: req.params.id
  })  
  .then(preventivo => {    
      var newdoc = new Preventivi(preventivo);
      newdoc._id = mongoose.Types.ObjectId();
      delete newdoc.__v;
      newdoc.save();
      console.log(newdoc._id)
     
      req.flash("msg_successo", "Preventivo clonato correttamente");
      res.redirect("/preventivi/dbpreventivi");
  });
});
//fine route clona preventivo

Html:

 <form  action="/preventivi/dbpreventivi/{{_id}}/clone?_method=POST" method="post">
            <input type="hidden" name="_method" value="POST">
            <input onclick="return confirm('Vuoi clonare il preventivo: {{cliente}} {{codice}} ?');"  type="submit" class="btn btn-warning btn-sm" value="Clona">
        </form>   

Solution

  • You can try add newdoc.isNew = true :

    //ROUTE CLONA PREVENTIVO
    app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
        Preventivi.findOne({
          _id: req.params.id
      })  
      .then(preventivo => {    
          var newdoc = new Preventivi(preventivo);
          newdoc._id = mongoose.Types.ObjectId();
          newdoc.isNew = true;      
          newdoc.save();
          console.log(newdoc._id)     
          req.flash("msg_successo", "Preventivo clonato correttamente");
          res.redirect("/preventivi/dbpreventivi");
      });
    });
    //fine route clona preventivo