Grabbing multiple database objects
-
Hi! I'm looking for a good way to store multiple objects, and be able to safely parse/edit them.
As-well as grab the objects by different data (ex: product_id, owner_uid, cost, etc.) such as you would be able to do with MySQL ("SELECT * FROMxxxx
WHERE data='value' ").Is it safe to just make an array of objects in a hash such as plugin:market:products and when I need to access it, grab the array parse it, remove/edit whatever data I need, and update the hash with the new array? Or would that be unsafe (Unsure how database calls are processed within NodeBB).
-
I'll take a stab at this.
Since Redis isn't relational, you'll need to mimic relational behaviour by creating additional database entries. In theory, you'll want to avoid doing this as much as possible since it involves creating lots of duplicate data.
First, store your hashes (objects) like below, with the last word being the object's 'primary key'.
plugin:market:product:apple
plugin:market:product:orange
Next, to mimic a relationship, create a
sorted set
where the values are your 'primary keys' and the scores are your 'secondary keys'plugin:market:products:cost
Now, if you want to find all objects that have a certain cost, you can search this set ByScore and retrieve an array of the keys to the objects you want.
Example:
var db = module.parent.require('./database'); var async = require('async'); // Create the entries. async.waterfall([ async.apply(db.setObject, 'plugin:market:product:apple', {name: 'Red Apple', cost: 10}), async.apply(db.setObject, 'plugin:market:product:orange', {name: 'Orange Orange', cost: 5}), async.apply(db.sortedSetAdd, 'plugin:market:products:cost', 10, 'apple'), async.apply(db.sortedSetAdd, 'plugin:market:products:cost', 5, 'orange') ], function () { // Find the product key with a cost between 6-10 inclusive. db.getSortedSetRangeByScore('plugin:market:products:cost', 0, 1, 6, 10, function (err, result) { // Assuming no errors, result should be: ['apple'] // Now get the hash. db.getObject('plugin:market:product:' + result[0], function (err, product) { // Should print: 'Red Apple' console.log(product.name); }); }); });
Is it safe to just make an array of objects in a hash such as plugin:market:products and when I need to access it, grab the array parse it, remove/edit whatever data I need, and update the hash with the new array? Or would that be unsafe (Unsure how database calls are processed within NodeBB).
No. Don't do it. Only store regular strings in hashes. Although you can do what you say by stringifying and parsing json, you're asking for trouble.
-
Wonderful explanation! You are always on point when it comes to explaining things! Thank you so much!
-
@Stackoverload Thanks! ^^