Get the _id of inserted document in Mongo database in NodeJS

Javascriptnode.jsMongodb

Javascript Problem Overview


I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:

// ...
collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId; // = ???
});
// ...

How can I get the _id of inserted object?

Is there any way to get the _id without getting latest object inserted _id?

Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.

Javascript Solutions


Solution 1 - Javascript

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Solution 2 - Javascript

There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.

Try:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});

and check the console to see what I mean.

Solution 3 - Javascript

As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:

db.collection("collection-name")
  .insertOne(document)
  .then(result => {
    console.log(result.insertedId);
  })
  .catch(err => {
    // handle error
  });

It's the same thing if you use callbacks.

Solution 4 - Javascript

I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.

collection.insert(objToInsert, function (err, result){
    if(err)console.log(err);
    else {
        console.log(result["ops"][0]["_id"]);
        // The above statement will output the id of the 
        // inserted object
       }
});

Solution 5 - Javascript

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

collection.save(function(err,room){
  var newRoomId = room._id;
  });

Solution 6 - Javascript

if you want to take "_id" use simpley

result.insertedId.toString() 

// toString will convert from hex

Solution 7 - Javascript

Now you can use insertOne method and in promise's result.insertedId

Solution 8 - Javascript

You could use async functions to get _id field automatically without manipulating data object:

async function save() {
  const data = {
    name: "John"
  }

  await db.collection('users').insertOne(data)

  return data
}

Returns data:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}

Solution 9 - Javascript

@JSideris, sample code for getting insertedId.

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });

Solution 10 - Javascript

Similar to other responses, you can grab the variable using async await, es6+ features.

const insertData = async (data) => {

  const { ops } = await db.collection('collection').insertOne(data)
  console.log(ops[0]._id)
  
}

Solution 11 - Javascript

Another way to do it in async function :

const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()

// Create.R.U.D
router.post('/new-order', async function (req, res, next) {

    // security check
    if (Object.keys(req.body).length === 0) {
        res.status(404).send({
            msg: "Error",
            code: 404
        });
        return;
    }

    try {

        // operations
        let orderNumber = await db.collection('orders').countDocuments()
        let number = orderNumber + 1
        let order = {
            number: number,
            customer: req.body.customer,
            products: req.body.products,
            totalProducts: req.body.totalProducts,
            totalCost: req.body.totalCost,
            type: req.body.type,
            time: req.body.time,
            date: req.body.date,
            timeStamp: Date.now(),

        }

        if (req.body.direction) {
            order.direction = req.body.direction
        }

        if (req.body.specialRequests) {
            order.specialRequests = req.body.specialRequests
        }

        // Here newOrder will store some informations in result of this process.
        // You can find the inserted id and some informations there too.
        
        let newOrder = await db.collection('orders').insertOne({...order})

        if (newOrder) {

            // MARK: Server response
            res.status(201).send({
                msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
                code: 201
            });

        } else {

            // MARK: Server response
            res.status(404).send({
                msg: `Order N°${number} not created`,
                code: 404
            });

        }

    } catch (e) {
        print(e)
        return
    }

})

// C.Read.U.D


// C.R.Update.D


// C.R.U.Delete



module.exports = router;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIonică BizăuView Question on Stackoverflow
Solution 1 - JavascriptIonică BizăuView Answer on Stackoverflow
Solution 2 - JavascriptgeorgedyerView Answer on Stackoverflow
Solution 3 - JavascriptSerjuiceView Answer on Stackoverflow
Solution 4 - JavascriptSidakView Answer on Stackoverflow
Solution 5 - JavascriptSaurabh Chandra PatelView Answer on Stackoverflow
Solution 6 - JavascriptHamit YILDIRIMView Answer on Stackoverflow
Solution 7 - JavascriptktretyakView Answer on Stackoverflow
Solution 8 - Javascriptkuzey beytarView Answer on Stackoverflow
Solution 9 - JavascriptPyae SoneView Answer on Stackoverflow
Solution 10 - JavascriptStephen RomeroView Answer on Stackoverflow
Solution 11 - JavascriptYohan W. DunonView Answer on Stackoverflow