title: Mongoose pre save hook set auto increment ID in document
body: <p>A couple of similar questions have been asked before but I was not able to get any of the solutions to work for this use case.</p>
  
  <p>I am trying to write a pre commit hook that generates an auto-increment ID number each time a new 'records' document is saved.</p>
  
  <p>The creation of the auto increment ID is working. I was able to verify that by checking the console.log.</p>
  
  <p>The problem is that the RecordID is not being set on the document that is saved. The document is saved with the correct values being set in the save() call, but not the RecordID being set in the pre save hook.</p>
  
  <p><strong>Records model</strong></p>
  
  <pre><code>async function getNextSequence(name) {
  
    let seq, result;
  
    try {
      result = await counters.findOneAndUpdate({
        _id: name
      }, {
        // Increment sequence by 1
        $inc: { seq: 1 }
      });
    }
    catch (error) {
      console.error(`getNextSequence failed ${error}`);
    }
  
    return result.seq;
  
  }
  
  // Pre save hook
  RecordsSchema.pre('save', (next) =&gt; {
    // Get document being saved
    let record = this;
  
    // Get next RecordID auto increment number
    getNextSequence('RecordID').then(nextID =&gt; {
      // Set RecordID
      if (nextID) {
        record.RecordID = nextID;
      }
      // nextID is showing up correctly
      // record object also shows up correctly in the log,
      // but it does NOT show up in the database
      console.log(`RecordsSchema.pre ${nextID} ${JSON.stringify(record)}`);
      next();
    }).catch((error) =&gt; {
      console.error(`getNextSequence failed ${error}`);
    });
  
  });
  </code></pre>
  
  <p><strong>Records save() call</strong></p>
  
  <pre><code>router.post('/', (req, res, next) =&gt; {
  
    let record = new records();
      record.Title = req.body.Title;
      record.Location = req.body.Location;
  
    record.save().then(record =&gt; {
      res.status(200).json(record);
    }).catch((error) =&gt; {
      console.log(`${origin} ${error}`);
      res.status(500).send('Server error');
    });
  
  });
  </code></pre>
  
  <p><strong>Result</strong></p>
  
  <p>The record Title and Location are being saved correctly. However, the RecordID is not being saved. I also tried with a post save hook and the same issue is happening.</p>
  
  <pre><code>RecordsSchema.post('save', (doc) =&gt; {
    // Get document being saved
    let record = doc;
  
    // Get next RecordID auto increment number
    getNextSequence('RecordID').then(nextID =&gt; {
      // Set RecordID
      if (nextID) {
        record.set( { RecordID: nextID } );
      }
      console.log(`RecordsSchema.post ${nextID} ${JSON.stringify(record)}`);
      //next();
    }).catch((error) =&gt; {
      console.error(`getNextSequence failed ${error}`);
    });
  
  });
  </code></pre>