How to use setOnInsert to place created/updated field in mongodb?
<p>I'm using a nodejs client to loop over input and create an array of values that will be handed off to the <code>bulkWrite</code> operation:</p>
<pre><code>  var updateVal = { sku: item.sku, name: item.name, updatedAt: new Date()};
  var insertVal = { sku: item.sku, name: item.name, createdAt: new Date(), updatedAt: new Date()};
  itemsToSave.push({
    updateOne: {
      filter: {
        sku: item.sku
      },
      //update: { $set: updateVal }, // works
      //update: { $setOnInsert: insertVal }, // works
      update: { $set: updateVal, $setOnInsert: insertVal }, // DOES NOT work
      upsert:true
    }
  });
</code></pre>
<p>But for some reason I can't mix <code>$set</code> and <code>$setOnInsert</code> ... when I run it, nothing happens, it is like a no-op. Is this a limitation of bulk operation?</p>
<p>I'm using node-mongodb-native/2.1 to work with mongodb 3.0.7</p>
<p>The docs for <a href="https://docs.mongodb.com/v3.0/reference/operator/update/setOnInsert/#example" rel="nofollow noreferrer">setOnInsert</a> suggest that this should be possible:</p>
<pre><code>...
  {
     $set: { item: &quot;apple&quot; },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
</code></pre>
<p>That's why my question is about using it with bulkWrite</p>
<h1>Update</h1>
<p>This worked:</p>
<pre><code>      update: {
        $currentDate: { updatedAt: true },
        $set: updateVal,
        $setOnInsert: {
          createdAt: new Date()
        }
      },
      upsert:true
</code></pre>
<p>thanks to the sample found via github code search: <a href="https://github.com/rainder/node-process-stat/blob/22899f49413314402645ae57bc691bd389d226bd/src/server/router/log.js#L49-L59" rel="nofollow noreferrer">https://github.com/rainder/node-process-stat/blob/22899f49413314402645ae57bc691bd389d226bd/src/server/router/log.js#L49-L59</a></p>