Collection.modify()
Modifies all objects in the table subset represented by this Collection instance.
Syntax
collection.modify(changes)
Parameters
changes |
Object containing changes to apply on all objects in the collection. Caller can supply a Function instead of Object.
|
Return Value
Promise where resolved value is the number of modified objects. If any object fails to be updated, the entire operation will fail and Promise will reject. To catch the error, call Promise.catch() on the returned Promise, else the error will bubble to the aborted transaction and if not caught there, finally bubble to db.on(“error”).
Remarks
Applies given changes to all objects in the collection.
If given changes is an Object, each key in the object represents a keyPath and each value the new value to set. A key path can be the name of a property or if containing periods (.) act as a path to a property in a nested object.
If the value is a function, the function will be called for each object so that the function may modify or delete any properties on the object. A function may also replace the object with another object by using this.value = otherObject. Finally, the function may also delete the object by doing delete this.value;
See samples below.
Error Handling
If any object fails to be modified or an exception occur in a callback function, entire operation will fail and transaction will be aborted.
If you catch the returned Promise, transaction will not abort, and you recieve a Dexie.ModifyError error object containing the following properties:
failures | Array of Error objects of all errors that have occurred |
failedKeys | Array of the keys of the failed modifications. This array will have the same order as failures so that failures[i] will always represent the failure of failedKeys[i] |
successCount | Number of successful modifications made. |
If you do NOT catch the returned Promise, and an error occur, the transaction will be aborted.
If you want to log the error but still abort the transaction, you must encapsulate the operation in a transaction() block and catch the transaction instead. It is also possible to catch the operation and call transaction.abort() in the catch() clause.
Sample
db.transaction("rw", db.friends, async () => {
// Mark bigfoots:
await db.friends.where("shoeSize").aboveOrEqual(47).modify({isBigfoot: 1});
// Log all bigfoots.
// Since in transaction, and prev operation is a write-operation, the below
// operation will be stalled until above operation completes, ensuring we
// get the result after the modification.
const bigfoots = await db.friends.where({isBigfoot: 1}).toArray();
console.log("Bigfoots:", bigfoots);
}).catch (Dexie.ModifyError, error => {
// ModifyError did occur
console.error(error.failures.length + " items failed to modify");
}).catch (error => {
console.error("Generic error: " + error);
});
Sample using Function
// Convert all shoeSize from european to american size:
db.friends.toCollection().modify(friend => {
friend.shoeSize *= 0.31; // (very approximate formula...., but anyway...)
});
Sample Replacing Object
The this pointer points to an object containing the property value. This is the same value as being sent as the first argument. To replace the object entirely you cannot use the value from the argument since “by ref” is not possible with javascript. Instead, use this.value = otherObj
to change the reference, as sample code below shows:
// Replace friend with another friend:
db.friends.where("isKindToMe").equals("no").modify(function(value) {
this.value = new Friend({name: "Another Friend"});
});
With arrow function (Supported since Dexie v1.3.4):
db.friends.where("isKindToMe").equals("no").modify((value, ref) => {
ref.value = new Friend({name: "Another Friend"});
});
Sample Deleting Object
// Delete all friends that have been mean.
db.friends.where("hasBeenMeanToMe").equals("yes").modify(function(value) {
delete this.value;
});
With arrow function (Supported since Dexie v1.3.4):
// Delete all friends that have been mean.
db.friends.where("hasBeenMeanToMe").equals("yes").modify((value, ref) => {
delete ref.value;
});
The sample above is equivalent to:
db.friends.where("hasBeenMeanToMe").equals("yes").delete();
Sample using Nested Key
In this sample, we modify a property that is a nested key (a key in a nested object). We include the schema and an example object in this example just to clarify how nested objects are used.
const db = new Dexie("FriendsDB");
db.version(1).stores({ friends: "++id, name, props.shoeSize, props.bigfoot"});
db.on("populate", function () {
db.friends.add({
name: "Zlatan",
props: {
shoeSize: 47,
bigfoot: "no" // Will be changed later ;)
}
});
});
db.transaction("rw", db.friends, async () => {
// Mark bigfoots:
await db.friends
.where("props.shoeSize").aboveOrEqual(47)
.modify({"props.bigfoot": "yes"});
// Log all bigfoots.
// Since in transaction, and prev operation is a write-operation, the
// below operation will be stalled until above operation completes,
// ensuring we get the result after the modification.
await db.friends.where("props.bigfoot").equals("yes").each(friend => {
console.log("Found bigfoot: " + friend.name);
});
}).catch (function (e) {
console.error(e);
});
Table of Contents
- API Reference
- Access Control in Dexie Cloud
- Add demo users
- Add public data
- Authentication in Dexie Cloud
- Best Practices
- Building Addons
- Collection
- Collection.and()
- Collection.clone()
- Collection.count()
- Collection.delete()
- Collection.desc()
- Collection.distinct()
- Collection.each()
- Collection.eachKey()
- Collection.eachPrimaryKey()
- Collection.eachUniqueKey()
- Collection.filter()
- Collection.first()
- Collection.keys()
- Collection.last()
- Collection.limit()
- Collection.modify()
- Collection.offset()
- Collection.or()
- Collection.primaryKeys()
- Collection.raw()
- Collection.reverse()
- Collection.sortBy()
- Collection.toArray()
- Collection.uniqueKeys()
- Collection.until()
- Compound Index
- Consistency in Dexie Cloud
- Consistent add() operator
- Consistent remove() operator
- Consistent replacePrefix() operator
- Consuming Dexie as a module
- Custom Emails in Dexie Cloud
- DBCore
- DBCoreAddRequest
- DBCoreCountRequest
- DBCoreCursor
- DBCoreDeleteRangeRequest
- DBCoreDeleteRequest
- DBCoreGetManyRequest
- DBCoreGetRequest
- DBCoreIndex
- DBCoreKeyRange
- DBCoreMutateRequest
- DBCoreMutateResponse
- DBCoreOpenCursorRequest
- DBCorePutRequest
- DBCoreQuery
- DBCoreQueryRequest
- DBCoreQueryResponse
- DBCoreRangeType
- DBCoreSchema
- DBCoreTable
- DBCoreTableSchema
- DBCoreTransaction
- DBCoreTransactionMode
- DBPermissionSet
- Deprecations
- Derived Work
- Design
- Dexie Cloud API
- Dexie Cloud API Limits
- Dexie Cloud Best Practices
- Dexie Cloud CLI
- Dexie Cloud Docs
- Dexie Cloud REST API
- Dexie Cloud Web Hooks
- Dexie Constructor
- Dexie.AbortError
- Dexie.BulkError
- Dexie.ConstraintError
- Dexie.DataCloneError
- Dexie.DataError
- Dexie.DatabaseClosedError
- Dexie.IncompatiblePromiseError
- Dexie.InternalError
- Dexie.InvalidAccessError
- Dexie.InvalidArgumentError
- Dexie.InvalidStateError
- Dexie.InvalidTableError
- Dexie.MissingAPIError
- Dexie.ModifyError
- Dexie.NoSuchDatabaseErrorError
- Dexie.NotFoundError
- Dexie.Observable
- Dexie.Observable.DatabaseChange
- Dexie.OpenFailedError
- Dexie.PrematureCommitError
- Dexie.QuotaExceededError
- Dexie.ReadOnlyError
- Dexie.SchemaError
- Dexie.SubTransactionError
- Dexie.Syncable
- Dexie.Syncable.IDatabaseChange
- Dexie.Syncable.IPersistentContext
- Dexie.Syncable.ISyncProtocol
- Dexie.Syncable.StatusTexts
- Dexie.Syncable.Statuses
- Dexie.Syncable.registerSyncProtocol()
- Dexie.TimeoutError
- Dexie.TransactionInactiveError
- Dexie.UnknownError
- Dexie.UnsupportedError
- Dexie.UpgradeError()
- Dexie.VersionChangeError
- Dexie.VersionError
- Dexie.[table]
- Dexie.addons
- Dexie.async()
- Dexie.backendDB()
- Dexie.close()
- Dexie.currentTransaction
- Dexie.debug
- Dexie.deepClone()
- Dexie.defineClass()
- Dexie.delByKeyPath()
- Dexie.delete()
- Dexie.derive()
- Dexie.events()
- Dexie.exists()
- Dexie.extend()
- Dexie.fakeAutoComplete()
- Dexie.getByKeyPath()
- Dexie.getDatabaseNames()
- Dexie.hasFailed()
- Dexie.ignoreTransaction()
- Dexie.isOpen()
- Dexie.js
- Dexie.name
- Dexie.on()
- Dexie.on.blocked
- Dexie.on.close
- Dexie.on.error
- Dexie.on.populate
- Dexie.on.populate-(old-version)
- Dexie.on.ready
- Dexie.on.storagemutated
- Dexie.on.versionchange
- Dexie.open()
- Dexie.override()
- Dexie.semVer
- Dexie.setByKeyPath()
- Dexie.shallowClone()
- Dexie.spawn()
- Dexie.table()
- Dexie.tables
- Dexie.transaction()
- Dexie.transaction()-(old-version)
- Dexie.use()
- Dexie.verno
- Dexie.version
- Dexie.version()
- Dexie.vip()
- Dexie.waitFor()
- DexieCloudOptions
- DexieError
- Docs Home
- Download
- EntityTable
- Export and Import Database
- Get started with Dexie in Angular
- Get started with Dexie in React
- Get started with Dexie in Svelte
- Get started with Dexie in Vue
- Hello World
- How To Use the StorageManager API
- Inbound
- IndexSpec
- Indexable Type
- IndexedDB on Safari
- Invite
- Member
- Migrating existing DB to Dexie
- MultiEntry Index
- PersistedSyncState
- Privacy Policy
- Promise
- Promise.PSD
- Promise.catch()
- Promise.finally()
- Promise.on.error
- Promise.onuncatched
- Questions and Answers
- Realm
- Releasing Dexie
- Road Map
- Road Map: Dexie 5.0
- Road Map: Dexie Cloud
- Role
- Run Dexie Cloud on Own Servers
- Sharding and Scalability
- Simplify with yield
- Support Ukraine
- SyncState
- Table
- Table Schema
- Table.add()
- Table.bulkAdd()
- Table.bulkDelete()
- Table.bulkGet()
- Table.bulkPut()
- Table.bulkUpdate()
- Table.clear()
- Table.count()
- Table.defineClass()
- Table.delete()
- Table.each()
- Table.filter()
- Table.get()
- Table.hook('creating')
- Table.hook('deleting')
- Table.hook('reading')
- Table.hook('updating')
- Table.limit()
- Table.mapToClass()
- Table.name
- Table.offset()
- Table.orderBy()
- Table.put()
- Table.reverse()
- Table.schema
- Table.toArray()
- Table.toCollection()
- Table.update()
- Table.where()
- The main limitations of IndexedDB
- Transaction
- Transaction.abort()
- Transaction.on.abort
- Transaction.on.complete
- Transaction.on.error
- Transaction.table()
- Tutorial
- Typescript
- Typescript (old)
- Understanding the basics
- UserLogin
- Version
- Version.stores()
- Version.upgrade()
- WhereClause
- WhereClause.above()
- WhereClause.aboveOrEqual()
- WhereClause.anyOf()
- WhereClause.anyOfIgnoreCase()
- WhereClause.below()
- WhereClause.belowOrEqual()
- WhereClause.between()
- WhereClause.equals()
- WhereClause.equalsIgnoreCase()
- WhereClause.inAnyRange()
- WhereClause.noneOf()
- WhereClause.notEqual()
- WhereClause.startsWith()
- WhereClause.startsWithAnyOf()
- WhereClause.startsWithAnyOfIgnoreCase()
- WhereClause.startsWithIgnoreCase()
- db.cloud.configure()
- db.cloud.currentUser
- db.cloud.currentUserId
- db.cloud.events.syncComplete
- db.cloud.invites
- db.cloud.login()
- db.cloud.logout()
- db.cloud.options
- db.cloud.permissions()
- db.cloud.persistedSyncState
- db.cloud.roles
- db.cloud.schema
- db.cloud.sync()
- db.cloud.syncState
- db.cloud.userInteraction
- db.cloud.usingServiceWorker
- db.cloud.version
- db.cloud.webSocketStatus
- db.members
- db.realms
- db.roles
- db.syncable.connect()
- db.syncable.delete()
- db.syncable.disconnect()
- db.syncable.getOptions()
- db.syncable.getStatus()
- db.syncable.list()
- db.syncable.on('statusChanged')
- db.syncable.setFilter()
- dexie-cloud-addon
- dexie-react-hooks
- liveQuery()
- unhandledrejection-event
- useLiveQuery()
- useObservable()
- usePermissions()