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.
Here's a basic example of using
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:
In this snippet, we use a callback function to inform us whether the addition was successful or not.
memcached.addwill not overwrite existing keys. If you want to overwrite regardless, consider using
Q: What happens if I try to add a key-value pair and the key already exists in the cache?
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.