Get the _id of inserted document in Mongo database in NodeJS

前端 未结 10 2004
半阙折子戏
半阙折子戏 2020-11-27 02:53

I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:

// ...
collection.         


        
10条回答
  •  忘掉有多难
    2020-11-27 03:35

    You could use async functions to get _id field automatically without manipulating data object:

    async function save() {
      const data = {
        name: "John"
      }
    
      await db.collection('users', data )
    
      return data
    }
    

    Returns data:

    {
      _id: '5dbff150b407cc129ab571ca',
      name: 'John'
    }
    

提交回复
热议问题