gpt4 book ai didi

javascript - 在 mongoDB 中,如何使用 async/await 获取使用 insertOne() 创建的对象的 id?

转载 作者:行者123 更新时间:2023-12-02 22:21:34 25 4
gpt4 key购买 nike

所以我正在创建一个用户对象并使用 async/await 将其插入到我的 mongo 数据库中。

像这样:

    await db.collection('users').insertOne({
name: 'testName',
age: 20
});
console.log('new user created');

我想从我刚刚添加的对象中获取 Id。我目前正在这样做:

    const newUser = await db.collection('users').insertOne({
name: 'testName',
age: 20
});
console.log('new user created');
console.log(newUser.ops[0]._id);

这正如我希望的那样工作,但它似乎不是最干净的方法。有没有更好的方法使用 async/await 获取新创建的对象的 id?

最佳答案

这是你的答案:

insertOne Returns: A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled. A field insertedId with the _id value of the inserted document.

示例:

{
"acknowledged" : true,
"insertedId" : ObjectId("56fc40f9d735c28df206d078")
}

Documentation HERE

关于javascript - 在 mongoDB 中,如何使用 async/await 获取使用 insertOne() 创建的对象的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com