Skip to content

Commit

Permalink
fix bug on remove with custom extractField
Browse files Browse the repository at this point in the history
A bug was preventing proper removal of documents when using a custom
extractField. This commit fixes it.
  • Loading branch information
lucaong committed Aug 13, 2020
1 parent 387bd11 commit 7b2a80c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/MiniSearch.js
Expand Up @@ -189,7 +189,9 @@ class MiniSearch {

fields.forEach(field => {
const fieldValue = extractField(document, field)
const tokens = tokenize(fieldValue == null ? '' : fieldValue.toString(), field)
if (fieldValue == null) { return }

const tokens = tokenize(fieldValue.toString(), field)

addFieldLength(this, shortDocumentId, this._fieldIds[field], this.documentCount - 1, tokens.length)

Expand Down Expand Up @@ -267,8 +269,11 @@ class MiniSearch {
throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`)
}

fields.filter(field => getOwnProperty(document, field) != null).forEach(field => {
const tokens = tokenize(extractField(document, field) || '', field)
fields.forEach(field => {
const fieldValue = extractField(document, field)
if (fieldValue == null) { return }

const tokens = tokenize(fieldValue.toString(), field)

tokens.forEach(term => {
const processedTerm = processTerm(term, field)
Expand Down
16 changes: 16 additions & 0 deletions src/MiniSearch.test.js
Expand Up @@ -172,6 +172,22 @@ describe('MiniSearch', () => {
expect(console.warn).not.toHaveBeenCalled()
})

it('removes documents when using a custom extractField', () => {
const extractField = (document, fieldName) => {
const path = fieldName.split('.')
return path.reduce((doc, key) => doc && doc[key], document)
}
const ms = new MiniSearch({ fields: ['text.value'], storeFields: ['id'], extractField })
const document = { id: 123, text: { value: 'Nel mezzo del cammin di nostra vita' } }
ms.add(document)

expect(() => {
ms.remove(document)
}).not.toThrowError()

expect(ms.search('vita')).toEqual([])
})

it('cleans up the index', () => {
const originalIdsLength = Object.keys(ms._documentIds).length
ms.remove(documents[0])
Expand Down

0 comments on commit 7b2a80c

Please sign in to comment.