Reputation: 116
So I am creating a user object and inserting it into my mongo database using async / await.
Like so:
await db.collection('users').insertOne({
name: 'testName',
age: 20
});
console.log('new user created');
I would like to get the Id from the object I have just added. I am currently doing this like so:
const newUser = await db.collection('users').insertOne({
name: 'testName',
age: 20
});
console.log('new user created');
console.log(newUser.ops[0]._id);
This works as I would like it to but it doesn't seem like the cleanest way to do this. Is there a better way to get the newly created object's id using async / await?
Upvotes: 0
Views: 761
Reputation: 451
Here is your answer:
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.
Example:
{
"acknowledged" : true,
"insertedId" : ObjectId("56fc40f9d735c28df206d078")
}
Upvotes: 1