As I venture through the land of NodeJS, I’ve found the wonder and magic of NPM, a package management tool for Javscript similar to ruby’s gems. Although there are nearly 100,000 packages on the main npmjs site (94,553 at time-of-writing), it seems there are still niches to be filled.
Recently, while working on a top secret side-project, I wanted to grab a random object from a MongoDB collection. I used the highly-extensible mongoose to set up my models and just needed to find a package somewhere with the desired functionality. I found such a package called mongoose-random, but, unfortunately, I was never able to get this plugin to work correctly. The plugin in question also needed to insert new columns on your tables, which I didn’t really want. So I decided to create a new package.
mongoose-simple-random is an incredibly easy way to include a random accessor on your mongoose models. All that’s required is adding the plugin to the schema before compiling the model:
1 2 3 4 5 6 7 8
Now I can ask the model for a single random element of the
Test model with a single call to
1 2 3 4 5 6
Need to find more than one? Use
findRandom to get an array:
1 2 3 4 5 6
Zowee! Just like the default
find methods, you can pass in optional filters, fields, and options:
1 2 3 4 5 6 7 8 9
Given 1000s of objects, performance is excellent. I haven’t tested it on larger-scale databases, but I wouldn’t mind seeing some performance tests in the future.