Skip to main content

.set()

The .set() method adds items to an unordered collection. Unlike objects where keys are explicitly named, sets automatically generate unique IDs for each item, making them perfect for lists, feeds, and collections.

Signature

Parameters

any
The item to add to the set. Can be:
  • Object: Creates a new node and adds it
  • GUN reference: Links an existing node
  • Primitive: Wraps it in a node automatically
  • Node with soul: Links by soul reference
function
Called after the item is addedSignature: function(ack)
  • ack.err - Error if the operation failed
  • ack.ok - Success confirmation
object
Advanced options passed to the underlying .put() operation

Return Value

Returns a GUN reference to the newly added item (not the set itself).

Examples

Add Objects to a Set

Add with Callback

Building a Chat Room

Social Media Feed

Return Value Usage

Implementation Details

From the source code (set.js:4-23):
The .set() method:
  1. Checks if the item is already a node (has a soul)
  2. For plain objects, creates a new node with auto-generated ID
  3. For GUN references, extracts the soul and creates a link
  4. Adds the link reference to the parent set
  5. Returns a reference to the added item

Auto-Generated IDs

Each item added with .set() gets a unique ID:

Sets vs Objects

Working with Sets

Limitations

Notes

  • .set() is perfect for collections where you don’t need to choose keys
  • Items are stored as object properties with auto-generated keys
  • Use .map() to iterate over all items in a set
  • The returned reference allows immediate chaining on the new item
  • Sets do not enforce uniqueness - the same data can be added multiple times
  • There is no built-in .unset() or remove method - set properties to null instead
  • Sets are unordered - use timestamps if you need chronological order