@@ -40,47 +40,49 @@ let mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };
4040// "user-account" with docker. "my-db" with docker-compose
4141let databaseName = "my-db" ;
4242
43- app . post ( '/update-profile' , function ( req , res ) {
43+ app . post ( '/update-profile' , async function ( req , res ) {
4444 let userObj = req . body ;
4545
46- MongoClient . connect ( mongoUrlDocker , mongoClientOptions , function ( err , client ) {
47- if ( err ) throw err ;
48-
46+ try {
47+ const client = await MongoClient . connect ( mongoUrlDocker , mongoClientOptions ) ;
4948 let db = client . db ( databaseName ) ;
5049 userObj [ 'userid' ] = 1 ;
5150
5251 let myquery = { userid : 1 } ;
5352 let newvalues = { $set : userObj } ;
5453
55- db . collection ( "users" ) . updateOne ( myquery , newvalues , { upsert : true } , function ( err , res ) {
56- if ( err ) throw err ;
57- client . close ( ) ;
58- } ) ;
54+ await db . collection ( "users" ) . updateOne ( myquery , newvalues , { upsert : true } ) ;
5955
60- } ) ;
61- // Send response
62- res . send ( userObj ) ;
56+ client . close ( ) ;
57+
58+ // Send response
59+ res . send ( userObj ) ;
60+ } catch ( err ) {
61+ console . error ( err ) ;
62+ res . status ( 500 ) . send ( 'Internal Server Error' ) ;
63+ }
6364} ) ;
6465
65- app . get ( '/get-profile' , function ( req , res ) {
66- let response = { } ;
67- // Connect to the db
68- MongoClient . connect ( mongoUrlDocker , mongoClientOptions , function ( err , client ) {
69- if ( err ) throw err ;
7066
71- let db = client . db ( databaseName ) ;
67+ app . get ( '/get-profile' , async function ( req , res ) {
68+ try {
69+ // Connect to the db
70+ const client = await MongoClient . connect ( mongoUrlDocker , mongoClientOptions ) ;
71+ const db = client . db ( databaseName ) ;
7272
73- let myquery = { userid : 1 } ;
73+ const myquery = { userid : 1 } ;
7474
75- db . collection ( "users" ) . findOne ( myquery , function ( err , result ) {
76- if ( err ) throw err ;
77- response = result ;
78- client . close ( ) ;
75+ const result = await db . collection ( "users" ) . findOne ( myquery ) ;
76+ const response = result || { } ;
7977
80- // Send response
81- res . send ( response ? response : { } ) ;
82- } ) ;
83- } ) ;
78+ client . close ( ) ;
79+
80+ // Send response
81+ res . send ( response ) ;
82+ } catch ( err ) {
83+ console . error ( err ) ;
84+ res . status ( 500 ) . send ( "Internal Server Error" ) ;
85+ }
8486} ) ;
8587
8688app . listen ( 3000 , function ( ) {
0 commit comments