mongojs icon indicating copy to clipboard operation
mongojs copied to clipboard

possible to get updated/created doc on upsert?

Open ralyodio opened this issue 9 years ago • 2 comments

I was expecting the 2nd argument to the callback to be the newly created or updated doc, but there is no 2nd argument:

I'm coming from nedb which supposedly has same API so this is probably wrong:

db.things.update({ hash: data.hash }, data, { upsert: true })
    .then((err, numReplaced, doc) => {
      if (numReplaced) {
        return console.log('replaced %s docs', numReplaced);
      }

         // how do i get num of docs updated and also the new docs?
      console.log(doc);
    })
    .catch(err => {
      return console.error(err, data);
    });

But I want to get number of docs replaced (if upserted) and also the new doc regardless of update or insert happened.

ralyodio avatar Dec 11 '16 08:12 ralyodio

Any updates on this?

t2wu avatar Jul 30 '17 10:07 t2wu

First as you use promises and mongojs does not support promises out of the box I guess you opened this issue in the wrong repository (did you mean the official mongodb driver?)

Mongodb does not support getting (updated, upserted) documents as a result of the update operation but returns a WriteResult (https://docs.mongodb.com/manual/reference/method/db.collection.update/)

The write result you'll receive in a callback as second argument looks somehow like this { n: 1, nModified: 0, upserted: [ { index: 0, _id: abeabeabeabeabeabeabeabe } ], ok: 1 }

You can use the _id value of the upserted array to query the documents after updating the db.

saintedlama avatar Aug 08 '17 08:08 saintedlama