-2

Please explain this JavaScript language construct:

cursor => cursor.map(doc => doc._key)

in this context

collection.all().then(
  cursor => cursor.map(doc => doc._key) // this line
).then(
  keys => console.log('All keys:', keys.join(', ')),
  err => console.error('Failed to fetch all documents:', err)
);

Don't understand the doc => doc._key as parameter to the map() function. Why will it not work with doc => { key: doc._key, name: doc.name}?

Jonathan Lam
  • 15,294
  • 14
  • 60
  • 85
Nick M
  • 2,010
  • 4
  • 25
  • 42

1 Answers1

1

Lets break it down by line: Also here is some documentation on arrow functions.

collection.all()

// give me all the documents in the collection

.then(

  cursor  

// take a cursor, which goes over each item in the collection

=> 

// you can think of this as "take the cursor as input into an anonymous function, and return..."

cursor.map(

// a map over the cursors output

doc => doc._key)

// each document the cursor finds, return the documents key

).then(

  keys => console.log('All keys:', keys.join(', ')),

// take the resulting keys, and console log their value

  err => console.error('Failed to fetch all documents:', err)

// if there are any errors, please log those as well.
);
Patrick Motard
  • 2,630
  • 2
  • 12
  • 23
  • Thank you so much Patrick, excellent answer. Now I will probably end up refactoring a lot of code :)) – Nick M Jul 26 '16 at 22:16
  • Sure! No problem. Please be careful to read through documentation though. There are some major gotcha's, including compatibility, and the meaning of "this" in context. Other than that, it's a pretty awesome syntax IMO. – Patrick Motard Jul 26 '16 at 22:18
  • Yes sir it sure is. Looks like I will have to spend a few more days reading, before jumping into node.js just like that. – Nick M Jul 26 '16 at 22:29