2016-07-21 11:31:08 -07:00
// Update a prepaid document, and the denormalized data on user documents
// Limits the properties allowed to be set, but does not perform validation on them. Use carefully!
// Usage
// ---------------
// In mongo shell
//
// > db.loadServerScripts();
2016-07-21 16:42:32 -07:00
// > updatePrepaid('<prepaid id string>', { endDate: "2017-07-01T00:00:00.000Z", maxRedeemers: 10, creator: '56141d0a7291607006ad8412' });
2016-07-21 11:31:08 -07:00
var updatePrepaid = function updatePrepaid ( stringID , originalUpdate ) {
try {
load ( './bower_components/lodash/dist/lodash.js' )
}
catch ( e ) {
2016-07-21 16:42:32 -07:00
print ( 'Lodash could not be loaded, ensure you are in codecombat project directory.' ) ;
2016-07-21 11:31:08 -07:00
return ;
}
try {
var id = ObjectId ( stringID ) ;
}
catch ( e ) {
print ( 'Invalid ObjectId given:' , stringID ) ;
return ;
}
var prepaid = db . prepaids . findOne ( { _id : id } ) ;
if ( ! prepaid ) {
print ( 'Prepaid not found' ) ;
return ;
}
2016-07-21 11:33:24 -07:00
print ( 'Found prepaid' , JSON . stringify ( _ . omit ( prepaid , 'redeemers' ) , null , ' ' ) ) ;
2016-07-21 16:42:32 -07:00
print ( '-- has' , _ . size ( prepaid . redeemers ) , 'redeemers.' ) ;
2016-07-21 11:31:08 -07:00
2016-07-21 16:42:32 -07:00
var prepaidUpdate = _ . pick ( originalUpdate , 'maxRedeemers' , 'startDate' , 'endDate' , 'creator' ) ;
if ( _ . isString ( prepaidUpdate . creator ) ) {
try {
prepaidUpdate . creator = ObjectId ( prepaidUpdate . creator ) ;
}
catch ( e ) {
print ( 'Invalid creator given:' , stringID ) ;
return ;
}
}
2016-07-21 11:31:08 -07:00
if ( _ . isEmpty ( prepaidUpdate ) ) {
2016-07-21 11:33:24 -07:00
print ( '\nSkipping prepaid update, nothing to update.' )
2016-07-21 11:31:08 -07:00
}
else {
2016-07-21 11:33:24 -07:00
print ( '\nUpdate prepaid' ,
2016-07-21 11:31:08 -07:00
JSON . stringify ( prepaidUpdate , null , ' ' ) ,
db . prepaids . update (
2016-07-22 09:33:44 -07:00
{ _id : id } ,
2016-07-21 11:31:08 -07:00
{ $set : prepaidUpdate }
)
)
}
2016-07-22 09:33:44 -07:00
var userUpdate = _ ( originalUpdate )
. pick ( 'startDate' , 'endDate' )
. transform ( function ( result , value , key ) { result [ 'coursePrepaid.' + key ] = value } )
. value ( ) ;
2016-07-21 11:31:08 -07:00
if ( _ . isEmpty ( userUpdate ) ) {
2016-07-21 11:33:24 -07:00
print ( '\nSkipping user update, nothing to update.' )
2016-07-21 11:31:08 -07:00
}
else {
2016-07-21 11:33:24 -07:00
print ( '\nUpdate users' ,
2016-07-21 11:31:08 -07:00
JSON . stringify ( userUpdate , null , ' ' ) ,
db . users . update (
{ 'coursePrepaid._id' : id } ,
2016-07-22 09:33:44 -07:00
{ $set : userUpdate } ,
{ multi : true }
2016-07-21 11:31:08 -07:00
)
) ;
}
} ;
db . system . js . save (
{
_id : 'updatePrepaid' ,
value : updatePrepaid
}
) ;