Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

possible to get updated/created doc on upsert? #326

Open
ralyodio opened this issue Dec 11, 2016 · 2 comments
Open

possible to get updated/created doc on upsert? #326

ralyodio opened this issue Dec 11, 2016 · 2 comments

Comments

@ralyodio
Copy link

ralyodio commented Dec 11, 2016

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.

@t2wu
Copy link

t2wu commented Jul 30, 2017

Any updates on this?

@saintedlama
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants