db.collection(tableName).save({}, {}, (err, doc)=>{ console.log(`Saved doc: ${JSON.stringify(doc)}`) }) 

displays:

 Saved doc: {"ok":1,"n":1} 

The record in the database is successfully created. How now to find out with what identifier it was saved then?)

I want to make sure that I don’t care if there is a record in the database, or if a new one is being created. For this purpose, it seems like save () is intended?

    1 answer 1

    For your case, you can use insert instead of save , without specifying _id they work the same way. But, unlike save , insert returns including id for the documents inserted into the collection:

      db.collection(tableName).insert({}, (err, doc)=>{ console.log(`Saved doc: ${JSON.stringify(doc.insertedIds[0])}`) }); 

    If _id is specified in the inserted document, it will either be inserted (if there is no document with this _id yet), or an error will occur. Also insert has an option flag upsert , if it is set, then if _id matches, the _id will be rewritten instead of an error.

    insert also allows you to insert multiple documents at once, if you pass it an array of documents from the first argument. Therefore, the result is an array _id (for the case of inserting a single document, simply take the first element: insertedIds[0] ).