@@ -56,6 +56,21 @@ function generateMongoDBURL(options) {
56
56
}
57
57
}
58
58
59
+ /*!
60
+ * Tries to get the context and patch the function passed as argument
61
+ * @param {Function } the function to patch
62
+ * @param {String } [scopeName=loopback] the scope name
63
+ * @returns {Function } the function patched
64
+ */
65
+ function patchWithContext ( fn , scopeName ) {
66
+ scopeName = scopeName || 'loopback' ;
67
+ var ns = process && process . context && process . context [ scopeName ] ;
68
+ if ( ns && ns . bind ) {
69
+ fn = ns . bind ( fn ) ;
70
+ }
71
+ return fn ;
72
+ }
73
+
59
74
/**
60
75
* Initialize the MongoDB connector for the given data source
61
76
* @param {DataSource } dataSource The data source instance
@@ -285,6 +300,7 @@ MongoDB.prototype.execute = function(model, command) {
285
300
var args = [ ] . slice . call ( arguments , 2 ) ;
286
301
// The last argument must be a callback function
287
302
var callback = args [ args . length - 1 ] ;
303
+ callback = patchWithContext ( callback ) ;
288
304
289
305
// Topology is destroyed when the server is disconnected
290
306
// Execute if DB is connected and functional otherwise connect/reconnect first
@@ -1061,7 +1077,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
1061
1077
} else if ( filter . offset ) {
1062
1078
cursor . skip ( filter . offset ) ;
1063
1079
}
1064
- cursor . toArray ( function ( err , data ) {
1080
+ cursor . toArray ( patchWithContext ( function ( err , data ) {
1065
1081
if ( self . debug ) {
1066
1082
debug ( 'all' , model , filter , err , data ) ;
1067
1083
}
@@ -1085,7 +1101,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
1085
1101
} else {
1086
1102
callback ( null , objs ) ;
1087
1103
}
1088
- } ) ;
1104
+ } ) ) ;
1089
1105
}
1090
1106
} ;
1091
1107
@@ -1229,7 +1245,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio
1229
1245
1230
1246
this . execute ( model , 'findAndModify' , { _id : oid } , [
1231
1247
[ '_id' , 'asc' ] ,
1232
- ] , data , { } , function ( err , result ) {
1248
+ ] , data , { } , patchWithContext ( function ( err , result ) {
1233
1249
if ( self . debug ) {
1234
1250
debug ( 'updateAttributes.callback' , model , id , err , result ) ;
1235
1251
}
@@ -1241,7 +1257,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio
1241
1257
self . setIdValue ( model , object , id ) ;
1242
1258
object && idName !== '_id' && delete object . _id ;
1243
1259
cb && cb ( err , object ) ;
1244
- } ) ;
1260
+ } ) ) ;
1245
1261
} ;
1246
1262
1247
1263
function errorIdNotFoundForUpdate ( modelvalue , idValue ) {
0 commit comments