Reputation: 3524
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
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
Reputation: 1590
As nodejs is non blocking so the order of execution will be like this
let id;
console.log("id", id);
At this point id is undefined
so id undefined
is printeddb.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
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