.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 failedack.ok- Success confirmation
object
Advanced options passed to the underlying
.put() operationReturn Value
Returns a GUN reference to the newly added item (not the set itself).Examples
Add Objects to a Set
Add with Callback
Link Existing Nodes
Building a Chat Room
Social Media Feed
Return Value Usage
Implementation Details
From the source code (set.js:4-23):.set() method:
- Checks if the item is already a node (has a soul)
- For plain objects, creates a new node with auto-generated ID
- For GUN references, extracts the soul and creates a link
- Adds the link reference to the parent set
- 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 tonullinstead - Sets are unordered - use timestamps if you need chronological order