Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add documents to lunr index after assignment (TypeError: idx.add is not a function)

I'm trying to create a lunr index and be able to add documents to it after being assigned. This is a slightly simplified version of what I'm trying to do:

var documents = [{
  'id': '1',
  'content': 'hello'
}, {
  'id': '2',
  'content': 'world'
}, {
  'id': '3',
  'content': '!'
}];

var idx = lunr(function() {
  this.ref('id');
  this.field('content');
});

for (var i = 0; i < documents.length; ++i) {
  idx.add(documents[i]);
}

This is giving me the following error: TypeError: idx.add is not a function. I've seen multiple tutorials saying this is how you're supposed to be able to do it.

It only works for me though if I add the documents when assigning idx;

var documents = [{
  'id': '1',
  'content': 'hello'
}, {
  'id': '2',
  'content': 'world'
}, {
  'id': '3',
  'content': '!'
}];

var idx = lunr(function() {
  this.ref('id');
  this.field('content');

  for (var i = 0; i < documents.length; ++i) {
    this.add(documents[i]);
  }
});

I'm still a javascript noob so this might not be related to lunr necessarily.

like image 998
user3163192 Avatar asked May 18 '17 14:05

user3163192


1 Answers

The tutorial you linked to is for an older version of Lunr. The latest version requires you to add all documents to the index within the function you pass to the lunr function. In other words, your second example is correct for the latest version of Lunr.

There is a guide on upgrading to the latest version which should hopefully cover the difference between the old versions from that (and other) tutorials and the latest version.

like image 96
Oliver Nightingale Avatar answered Nov 07 '22 01:11

Oliver Nightingale