Skip to content

AbdelrahmanHafez/mongoose-cast-aggregation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

1f65e29 · Jul 7, 2022

History

53 Commits
Jul 6, 2022
Jul 6, 2022
Dec 27, 2019
May 30, 2020
Dec 27, 2019
May 30, 2020
Mar 9, 2021
Jul 7, 2022
Jul 6, 2022
May 30, 2020
Jul 7, 2022

Repository files navigation

Mongoose Cast Aggregation

A mongoose plugin that casts aggregation pipelines whenever possible.

Build Status Coverage Status NPM version

NPM

Getting Started

Run:

npm install mongoose-cast-aggregation

Inject the plugin into mongoose:

const mongoose = require('mongoose');
const castAggregation = require('mongoose-cast-aggregation');

mongoose.plugin(castAggregation); 

Now mongoose will cast the $match stage whenever possible. It casts the $match stage as long as no stage before it changed the resulting document shape from the original schema (e.g. $match, $limit, $sort, $skip, $sample, $search, and $searchMeta). It also casts query on $geoNear stages.

// After injecting the plugin
const discountSchema = new Schema({
  expiresAt: Date,
  amount: Number
});

const Discount = mongoose.model('Discount', discountSchema);

const discounts = await Discount.aggregate([
  // Will cast the amount to a number, and the timestamp to a date object
  { $match: { expiresAt: { $lt: Date.now() }, amount: '20' } }
]);

This works as well:

const discounts = await Discount.aggregate([
  { $sort: { amount:-1 } },
  { $skip: 20 },
  // Will cast the stage below to a date object, because the document shape hasn't changed yet.
  { $match: { expiresAt: { $lt: Date.now() } } },

  // Will cast this one to numbers as well.
  { $match: { amount: { $gt: '80', $lt: '200' } } },
  { $project: { amountInUSD: '$amount' } },

  // Will ***NOT*** cast this one, because we used a stage that changed the shape of the document.
  // so using the string '100' here will not work, will have to use the correct type of number in order to get results.
  { $match: { amountInUSD: { $gt: 100 } } }
]);

About

A mongoose plugin that casts aggregation stages whenever possible.

Resources

Stars

Watchers

Forks

Packages

No packages published