admin管理员组

文章数量:1317909

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

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

Share Improve this question edited Jun 26, 2020 at 19:23 namar sood 1,5901 gold badge10 silver badges17 bronze badges asked Jun 26, 2020 at 18:59 Igor CovaIgor Cova 3,5245 gold badges34 silver badges60 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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);
})();

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

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?

本文标签: javascriptMongoDb insertOne and return get idStack Overflow