@kos-ng-it-konsult/mongo-aggregator
v0.0.1
Published
An aggregator package for KOS NG IT Konsult
Downloads
2
Maintainers
Readme
@kos-ng-it-konsult/mongo-aggregator
This is a mongodb aggregator package for KOS NG IT Konsult.
Quick Start
Install
$ npm i --save @kos-ng-it-konsult/mongo-aggregator
Basic Usage
"use strict";
const mongoose = require('mongoose'); // run npm install --save mongoose
const lib = require('../index');
const db = mongoose.connect(`mongodb://127.0.0.1:27017/test`, {
useFindAndModify: false,
useNewUrlParser: true,
useCreateIndex: true
});
const FormSchema = new mongoose.Schema({
name: { type: String, required: true },
code: { type: String, required: true }
});
const FormModel = mongoose.model("Form", FormSchema);
const StudentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, required: true },
gender: { type: String, required: true },
form_id: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Form" }
});
const StudentModel = mongoose.model("Student", StudentSchema);
const aggregator = new lib().build();
aggregator
.addStage('match', { name: { $in: [ 'femi' ] } })
.addStage('lookup', {
from: 'forms',
localField: 'form_id',
foreignField: '_id',
as: 'form'
})
.addStage('unwind', '$form')
.addStage('match', { 'form.name': { $in: [ 'form 1' ] } })
.addStage('project', [
'_id', 'name', 'age', 'gender',
{ name: 'form', value: '$form.name' }
]);
const dataAggregator = aggregator.output();
StudentModel.aggregate(dataAggregator).exec().then(data => {/*...*/}).catch(error => {/*...*/});
Running the Example
To run the example, first install mongoose
using$ npm install --save mongoose
Then run the sample command$ node ./example/sample.js
Running Tests
Run$ npm test