0.3.1 • Published 2 years ago

mongoose-cast-aggregation v0.3.1

Weekly downloads
1,619
License
ISC
Repository
github
Last release
2 years ago

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

2 years ago

0.3.1

2 years ago

0.2.1

2 years ago

0.2.0

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago