'use strict';

const mongo = require('mongo');
const co = require('co');
const dataCollection = mongo.connect().then(db => db.collection('data'));

const defaultSearchEmOptions = {
    limit: 1e3,
    precision: 100
};
const searchEm = co.wrap(function* searchEm(value, options) {
    if (typeof value !== 'number') {
        throw new TypeError('value must be a number');
    }
    options = Object.assign({}, defaultSearchEmOptions, options);

    if (options.limit > 1e4) options.limit = 1e4;
    if (options.limit < 1) options.limit = 1;

    let error=value / 1e6 * options.precision;
    
    const data = yield dataCollection;
    const searchBottom = data.find({em: {$lte: value, $gte: value - error}}).sort({em: -1}).limit(options.limit).project({_id: -1, em: 1, mf: 1}).toArray();
    const searchTop = data.find({em: {$gt: value, $lte: value + error}}).sort({em: 1}).limit(options.limit).project({_id: -1, em: 1, mf: 1}).toArray();
    const results = yield Promise.all([searchBottom, searchTop]);

    const uniqueMFs = new Map();
    results.forEach(function treatResult(result) {
        for (const resultValue of result) {
            let element = uniqueMFs.get(resultValue.mf);
            if (!element) {
                element = {
                    mf: resultValue.mf,
                    em: resultValue.em,
                    ppm: Math.abs(resultValue.em - value) / value * 1e6,
                    total: 0
                };
                uniqueMFs.set(resultValue.mf, element);
            }
            element.total++;
        }
    });

    const finalResult = Array.from(uniqueMFs.values());
    finalResult.sort((a, b) => a.ppm - b.ppm);
    return finalResult;
});

exports.search = {
    em: searchEm
};

const moleculesEm = co.wrap(function* moleculesEm(value) {
    if (typeof value !== 'number') {
        throw new TypeError('value must be a number');
    }

    const data = yield dataCollection;
    const result = yield data.find({em: value}).project({_id: 1, iupac: 1, ocl: 1}).limit(10000).toArray();
    return result.map(el => {
        return {
            id: el._id,
            iupac: el.iupac,
            ocl: el.ocl
        };
    });
});

const moleculesMf = co.wrap(function* moleculesMf(value) {
    if (typeof value !== 'string') {
        throw new TypeError('value must be a string');
    }

    const data = yield dataCollection;
    const result = yield data.find({mf: value}).project({_id: 1, iupac: 1, ocl: 1}).limit(10000).toArray();
    return result.map(el => {
        return {
            id: el._id,
            iupac: el.iupac,
            ocl: el.ocl
        };
    });
});

exports.molecules = {
    em: moleculesEm,
    mf: moleculesMf
};

@@ -2155,32 +2155,55 @@
      ocl: el.ocl
+,%0A            mf: el.mf
 %0A        %7D;%0A    
@@ -2639,16 +2639,39 @@
 : el.ocl
+,%0A            mf: el.mf
 %0A       

Add mf in answer