kyleawayan
kyleawayan

Reputation: 183

MongoDB updateOne returning null for upsertedId

I'm trying to get the upsertedId for the updated document, but it's returning null.

Here's the function for updating a document and trying to return result.upsertedId:

 async function run() {
          try {
            await client.connect()
            const collection = client.db("database").collection("collection")
            const filter = { username: `${username}`}
            const options = { upsert: true };
            const updateDoc = {
              $set: { date: new Date(), topartists: data.body.items, toptracks: toptracks }
            };
            await collection.updateOne(filter, updateDoc, options)
              .then(result => {
                console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`)
                console.log(result.upsertedId)
              })
            console.log('done1')
          } finally {
            await client.close();
          }
        }

and here's the console output of the function:

1 document(s) matched the filter, updated 1 document(s)
null
done1

I'm just starting with MongoDB, and the end goal here is to get _id. It works there is nothing in my database (when it has to make a new document instead of updating one).

Upvotes: 3

Views: 3139

Answers (1)

Gibbs
Gibbs

Reputation: 22974

That will not be the case.

Your log clearly says - your query matched 1 document and it updated one document.

If your update results in insert, then response of your update operation will have upsert ids. - Means, matched count is 0.

Upvotes: 3

Related Questions