Skip to content

Commit

Permalink
use Promise.all
Browse files Browse the repository at this point in the history
  • Loading branch information
rharlev committed Mar 15, 2020
1 parent 59a0f44 commit a349ef2
Showing 1 changed file with 21 additions and 17 deletions.
38 changes: 21 additions & 17 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,25 +34,29 @@ const xmeta = async (req, res, next) => {
let query = {};
query['_box'] = req.params.boxId;

// get record count
const record_count = await Data.countDocuments(query).exec();
const result = {
"_count": record_count
}

if (record_count > 0) {
// get first _createdOn
const record_createdOn = await Data.findOne(query).sort('_createdOn').exec();
const createdOn = record_createdOn["_createdOn"]
if (createdOn) result["_createdOn"] = createdOn
const promises = [
Promise.resolve(Data.countDocuments(query).exec()),
Promise.resolve(Data.findOne(query).sort('_createdOn').exec()),
Promise.resolve(Data.findOne(query).sort('-_updatedOn').exec())
];

const result = {}
Promise.all(promises).then(function(values) {
result["_count"] = values[0];

if (values[0] > 0) {
// get first _createdOn
const createdOn = values[1]["_createdOn"];
if (createdOn) result["_createdOn"] = createdOn;

// get last _updatedOn
const updatedOn = values[2]["_updatedOn"];
if (updatedOn) result["_updatedOn"] = updatedOn;
}

// get last _updatedOn
const record_updatedOn = await Data.findOne(query).sort('-_updatedOn').exec();
const updatedOn = record_updatedOn["_updatedOn"]
if (updatedOn) result["_updatedOn"] = updatedOn
}
res.json(result);
});

res.json(result);
} catch (error) {
next(error);
}
Expand Down

0 comments on commit a349ef2

Please sign in to comment.