@@ -40,47 +40,49 @@ let mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };
40
40
// "user-account" with docker. "my-db" with docker-compose
41
41
let databaseName = "my-db" ;
42
42
43
- app . post ( '/update-profile' , function ( req , res ) {
43
+ app . post ( '/update-profile' , async function ( req , res ) {
44
44
let userObj = req . body ;
45
45
46
- MongoClient . connect ( mongoUrlDocker , mongoClientOptions , function ( err , client ) {
47
- if ( err ) throw err ;
48
-
46
+ try {
47
+ const client = await MongoClient . connect ( mongoUrlDocker , mongoClientOptions ) ;
49
48
let db = client . db ( databaseName ) ;
50
49
userObj [ 'userid' ] = 1 ;
51
50
52
51
let myquery = { userid : 1 } ;
53
52
let newvalues = { $set : userObj } ;
54
53
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 } ) ;
59
55
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
+ }
63
64
} ) ;
64
65
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 ;
70
66
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 ) ;
72
72
73
- let myquery = { userid : 1 } ;
73
+ const myquery = { userid : 1 } ;
74
74
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 || { } ;
79
77
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
+ }
84
86
} ) ;
85
87
86
88
app . listen ( 3000 , function ( ) {
0 commit comments