title: Creating MongoDB documents inside chained Promisified functions
body: <p>An app runs a process every 15 minutes that creates many output files with the following format:</p>
  
  <pre><code>&lt;timestamp&gt;-&lt;piece-code&gt;.txt
  </code></pre>
  
  <p>All files created by the process will share the "timestamp" component but the "piece-code" will differ, meaning I have a relationship of <strong>One</strong> Timestamp to <strong>Many</strong> Pieces, that I want to save in mongodb as:</p>
  
  <pre><code>"Registry" { time: (numeric) }
  "Piece" { file: (string), piece: (string), registry: (reference) }
  </code></pre>
  
  <p>In the process I want to find if a <strong>timestamp</strong> exists already before creating it to avoid duplicates, but my code seems to fail to do this.</p>
  
  <p>Thanks in advance for your help!</p>
  
  <pre><code>const mongoose = require('mongoose');
  
  const Registry = require('../model/Registry');
  const Piece = require('../model/Piece');
  mongoose.Promise = require('bluebird');
  
  // Set up default mongoose connection
  let mongoDB = 'mongodb://127.0.0.1/numbers';
  mongoose.connect(mongoDB, {
    useMongoClient: true
  });
  
  //Get the default connection
  let db = mongoose.connection;
  
  // Bind connection to error event
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));
  
  
  // Error handler
  let error = (err) =&gt; {
    console.log("** Error: ", err);
    db.close();
  };
  
  // Finish routine
  let finish = () =&gt; {
      console.log("I have finished");
      db.close();
  };
  
  
  // Create a number if it does not exist already
  let newRegistry = (timestamp) =&gt; {
    return new Promise((resolve, reject) =&gt; {
      Registry.count({}).then((c) =&gt; { console.log(c) })
  
      // Does this Registry exist?
      Registry.findOne({ time: timestamp })
        .then((reg, err) =&gt; {
          if (err) {
            reject(err);
          }
          // Create when it does not exist
          if (!reg) {
            Registry.create({
              time: timestamp
            }).then((doc, err) =&gt; {
              if (err) {
                reject(err);
              }
              resolve(doc._id);
            })
            .catch(error);
          } else {
            // Else, resolve
            resolve(reg._id);
          }
  
        });
    });
  }
  
  let newPiece = (registryId, filename, piece) =&gt; {
    return Piece.create({
      registry: mongoose.Types.ObjectId(registryId),
      file: filename,
      piece: piece
    });
  
  };
  
  let createRegs = (files) =&gt; {
    return new Promise((resolve, reject) =&gt; {
      let promises = [];
      let total = files.length;
      for (let i=0; i&lt;total; i++) {
        let fileAr = files[i].split("-");
        let time = fileAr[0];
        let piece = fileAr[1];
  
        let promise = newRegistry(time)
          .then((regId) =&gt; {
            return newPiece(regId, files[i], piece);
          });
  
        promises.push(promise);
      }
  
      Promise.all(promises)
        .then(() =&gt; {
          resolve();
        })
        .catch(error);
    });
  }
  
  
  // Register input time and file pieces: one "time" can have many "pieces"
  let filenames = ["1512473256-e.txt", "1512471758-a.txt", "1512471892-a.txt", "1512471758-b.txt"];
  
  // Must end up with 3 "Registry" and 4 "Piece" documents
  createRegs(filenames)
    .then(finish)
    .catch(error);
  </code></pre>