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
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?
本文标签: javascriptMongoDb insertOne and return get idStack Overflow
版权声明:本文标题:javascript - MongoDb insertOne and return get _id - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742024661a2415314.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论