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
3 Answers
Reset to default 6As nodejs is non blocking so the order of execution will be like this
let id;
console.log("id", id);
At this point id isundefined
soid undefined
is printed- 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?