使用 Loopback 从 MongoDB 获取随机对象

Getting a random object from MongoDB using Loopback

我在网上搜索了一个关于如何使用环回从 MongoDB 获取多个随机对象的好答案。

我寻找一种显示随机数据的好方法的原因是为了像 "Interesting in this book/recommendation" 这样的模块,它随机显示 4-5 本书。

希望你们能指导我如何以最好的方式解决问题。

要使用 Loopback 从 MongoDB 获取随机对象,您需要创建一个自定义端点(在您的 model.js 文件中),如下所示:

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);
      });
    });
}

将 "Model" 替换为您的型号名称。注意:需要大写!如果您不知道您的集合名称,如果 Loopback 创建它,它通常与您的模型名称相同(不大写)。

要使此端点显示在资源管理器中,请将其也添加到您的 model.js 文件中:

Model.remoteMethod(
    'random', {
        http: {
            path: '/random',
            verb: 'get'
        },
        description: 'Gets one random thing',
        returns: {
            arg: 'randomThings',
            type: 'json'
        }
    });

我在此示例应用程序中有一个此端点的示例:jeopardy-mongo-api