Node Memcached Add (Detailed Guide w/ Code Examples)

Use Case(s)

In Node.js applications, the memcached add function is typically used when you need to store key-value pairs in a memcached server. This function only succeeds if the server doesn't already hold data for this key. It's useful when you want to ensure no existing data gets overwritten.

Code Examples

Here's a basic example of using memcached.add:

const Memcached = require('memcached'); let memcached = new Memcached("localhost:11211"); let key = "username"; let value = "testUser"; // The '10' is the lifetime of the cache in seconds. memcached.add(key, value, 10, function(err) { // handle error if(err) console.error(err); });

In this code, we are connecting to a local memcached server and trying to add a key-value pair username:testUser. If the operation is successful and there was no previous data associated with username, the data will be stored in the cache for 10 seconds.

A more complex example might involve checking if the addition was successful or not:

memcached.add(key, value, 10, function(err) { if(err) { console.error("Failed to add:", err); } else { console.log("Added successfully"); } });

In this snippet, we use a callback function to inform us whether the addition was successful or not.

Best Practices

  1. Always handle potential errors in your callbacks to prevent unexpected behavior.
  2. When adding items to memcached, consider their expiration carefully. Too short might mean they expire before needed, but too long could waste memory.

Common Mistakes

  1. Attempting to add a key that already exists. memcached.add will not overwrite existing keys. If you want to overwrite regardless, consider using memcached.set instead.
  2. Not checking or handling errors that may arise when trying to connect to the memcached server or add data.


Q: What happens if I try to add a key-value pair and the key already exists in the cache?

A: The add function will not update the value of the key. It will simply ignore the command and your existing data tied to that key remains safe.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.