I have searched all over the web for a good answer to how I can get multiple random objects from MongoDB using Loopback.
The reason why I search for a good way to show random data is for a module like "Interesting in this book/recommendation", that shows 4-5 books randomly.
Hopefully, you guys can bring me in a good direction how to solve the issue the best way.
To get a random object from MongoDB using Loopback, you will need to create a custom endpoint (in your model.js file), like so:
Model.random = function(cb){
// this next line is what connects you to MongoDB
Model.getDataSource().connector.connect(function(err, db) {
var collection = db.collection('YOURCOLLECTIONNAMEHERE');
//the below is MongoDB syntax, it basically pulls a
//random sample of size 1 from your collection
collection.aggregate([
{ $sample: { size: 1 } }
], function(err, data) {
if (err) return cb(err);
return cb(null, data);
});
});
}
Replace "Model" with your model name. Note: it needs to be capitalized! If you don't know your collection name, if Loopback created it, it is usually the same as your model name (not capitalized).
To make this endpoint show up in the Explorer, add this to your model.js file too:
Model.remoteMethod(
'random', {
http: {
path: '/random',
verb: 'get'
},
description: 'Gets one random thing',
returns: {
arg: 'randomThings',
type: 'json'
}
});
I have an example of this endpoint in this sample application: jeopardy-mongo-api