I’m working on creating an automated system for database operations using a JavaScript library, but I’m running into issues when trying to use dynamic property access in my functions.
Whenever I attempt to perform operations like modify or remove, the code fails to execute properly. For example, when trying to modify a record, I receive this error:
Promise.js:840 Unhandled rejection: TypeError: Cannot read property ‘modify’ of undefined
Similar issues occur with other operations like remove.
Here’s a simplified example showing my problem:
<!doctype html>
<html>
<head>
<script>
var database = new DatabaseLib("UserDB");
database.version(1).stores({
users: '++id,username,email'
});
database.users.add({
username: 'Sarah',
email: '[email protected]' })
.then(()=>{
processData(database,'users')
});
function processData(db, tableName){
// This doesn't work: db.tableName.remove(1)
db[tableName].remove(1) // fails to execute
db.tableName.modify(1, {username:"John"}).then(()=>{
console.log('updated successfully'); // never runs
})
.catch(error=>{
console.log(error);
});
}
database.users.each(item=>{
console.log(item)
})
</script>
</head>
</html>
What’s the correct way to use dynamic property names in this context?
yeah, ur mixing the syntax. db[tableName].remove(1) is right, but then u used db.tableName.modify() which treats ‘tableName’ as text, not var. should be db[tableName].modify(1, {username:"John"}). once u go dynamic, stick with it throughout.
I ran into this same issue building a multi-tenant app with runtime table names. You’re mixing up your property access methods in processData. You correctly use db[tableName].remove(1) for the remove operation, but then switch to dot notation with db.tableName.modify(). That’s trying to access a literal ‘tableName’ property instead of using your variable. Stick with bracket notation: db[tableName].modify(1, {username:"John"}). Also, wrap your dynamic operations in try-catch blocks - they’ll fail silently if the table name’s invalid or you lose the database connection.
The bracket notation works fine for dynamic property access - you’re just mixing syntaxes. In your processData function, you’ve got db[tableName].remove(1) which is right, but then you switch to db.tableName.modify() right after. That treats ‘tableName’ as a literal property name, not the variable. Stick with bracket notation throughout: db[tableName].modify(1, {username:"John"}). I’ve done this exact same thing when refactoring - it’s super easy to miss when you’re switching between direct and dynamic access. Just make sure all your database operations in that function use brackets with the variable, not dots with the literal string.