I have this object called 'ctx.instance' which has the following properties:
firstName: 'Ron',
lastName: 'Santo',
minor: true,
accepted: false,
emailChanged: false,
organizationId: 000000000000000001000001,
isDeleted: false,
userId: 55e17a46e410f9603cea515b
This object was passed into my function. I need to strip off the 'emailChanged' property before saving it to the database. So I did this:
delete ctx.instance.emailChanged;
The delete returns 'true' which means the property doesn't exist.
The following statement after the delete yields false which also means it should be gone:
'emailChanged' in ctx.instance
Yet, if I do a console.log(ctx.instance), the 'emailChanged' property is still there and it gets saved to the database.
If I check the property's properties, it says it is configurable. If I do a console.log(ctx.instance.emailChanged) after the delete statement, it says 'undefined'.
Why is it still there?
I've searched all over the internet, tried tons of different things, and I can't find why this is occurring. This is happening within a Node environment.
UPDATE: The DB is Mongo. I'm using Loopback.js models and framework.
The data variable is the object submitted to the server from the client via a PUT. The data object was originally JSON but Loopback has made it a JavaScript object.
The code is within an operation hook so the save to the DB doesn't live within this function.
The 'delete' statement is the last statement within the function before I pass it back off to the framework.
Here is the minimum code for the hook:
module.exports = function( Member )
{
Member.observe( 'before save', upsertMember );
function upsertMember( ctx, next )
{
// displays 'true'
console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );
// displays 'false'
console.log( ctx.instance.emailChanged );
var isDeleted = delete ctx.instance.emailChanged;
// displays 'true'
console.log( isDeleted );
// displays 'false'
console.log( 'emailChanged' in ctx.instance );
// displays 'false'
console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );
// displays 'undefined'
console.log( ctx.instance.emailChanged );
// displays object properties including 'emailChanged'
console.log( ctx.instance );
// pass control back to loopback for upsert
// 'emailChanged' gets into MongoDB record
next();
}
}
If any of you know a JSFiddle type of environment that includes Loopback, I'll throw it in there.
Screenshot of my debugger watch right after the delete statement:
According to Loopback Operation Hooks
Removing unneeded properties
To remove unwanted properties (fields) from the context object, use the following:
ctx.instance.unsetAttribute('unwantedField');
This completely removes the field and prevents inserting spurious data into the database.
Should have done this:
ctx.instance.unsetAttribute('emailChanged');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With