How to obtain document that was just upserted in mongodb?

In the following command, where foos is a collection, I "upsert" a new item:

foos.update(criteria, 
  { $set: fooUpdate }, 
  { w: 1, upsert: true }, 
  function(err, upsertedFoo) {
    /* upsertedFoo is actually just count of updated/ inserted rows */
}

I would like to obtain the new document that was just created (if it was an update), or the existing document that was modified (if it was updated). If this is not possible, the _id of it will also suffice.

How can I get this?

NOTE: I am using the standard mongodb package.

The update function's callback will give you the updated document. For example:

foo.update(conditions, document, options, function(err, result) {
  if (err)
   throw new Error(err);
  console.dir(result);
}

If you use findAndModify with new:true you will get updated or new objects as result, it works with upsert.

http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/#return-new-document

I found this on the docs:

// Simple findAndModify command performing an upsert and returning the new document
// executing the command safely
collection.findAndModify({d:1}, [['b', 1]],
  {d:1, f:1}, {new:true, upsert:true, w:1}, function(err, doc) {
    assert.equal(null, err);
    assert.equal(1, doc.d);
    assert.equal(1, doc.f);
     db.close();
})

This 'new' option seems to be the key:

new {Boolean, default:false}

set to true if you want to return the modified object rather than the original. Ignored for remove.

Hope this helps