Igor Cova
Igor Cova

Reputation: 3524

MongoDb insertOne and return get _id

I tried to get _id inserted object:

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

});

console.log("id", id);

In console I see insertedId but how to get it outside then

after insertOne in console I see id undefind

Upvotes: 1

Views: 11210

Answers (3)

ibrahimijc
ibrahimijc

Reputation: 341

inserOne is an asynchronous function. The insertOne function is sent for execution in the background while your console.log(id) is printed before it. One thing is you can do it in the .then function

let id;
db.collection("collection-name")
  .insertOne(document)
  .then(result => {
  id = result.insertedId;
  console.log(result.insertedId);
  // here you have the acccess
  console.log("id", id);
}).catch(err => {
    
});

The other solution is to wait until the promise from insertOne is resolved using async/await.

async function insert(){
   let id;
   let result = await db.collection("collection-name").insertOne(document);
   id = result.insertedId;
   console.log(id)
}

await will only work with async functions

Upvotes: 1

namar sood
namar sood

Reputation: 1590

As nodejs is non blocking so the order of execution will be like this

  1. let id;
  2. console.log("id", id); At this point id is undefined so id undefined is printed
  3. At last this will be executed

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

});

but if you want to wait for the result before you can print it you can use async/wait

(async function () {
  let result = await db.collection("collection-name").insertOne(document);
  console.log("id", result.insertedId);
})();

Upvotes: 6

Mohamed Ali
Mohamed Ali

Reputation: 141

If your mongo collection structure has _id unless you have changed it. Maybe that causes the code to output undefined

Have you tried id = result._id instead?

Upvotes: 0

Related Questions