Skip to content

Instantly share code, notes, and snippets.

@joshuaalpuerto
Last active January 10, 2023 16:04
Show Gist options
  • Save joshuaalpuerto/6b818373c35e793e0895d00a275fa57c to your computer and use it in GitHub Desktop.
Save joshuaalpuerto/6b818373c35e793e0895d00a275fa57c to your computer and use it in GitHub Desktop.
Mongodb simple aggregate builder using Proxy
function generatePipeline(pipelines = []) {
const callable = () => {};
callable.pipelines = pipelines;
return new Proxy(callable, {
get(callable, propKey) {
return (props) => {
if (propKey === 'run') {
return callable.pipelines;
}
callable.pipelines.push({ [`$${propKey}`]: props });
return generatePipeline(callable.pipelines);
};
},
});
}
@joshuaalpuerto
Copy link
Author

const userPipeline = generatePipeline()
const pipelines = userPipeline
     .match({ _id: 'user123' })
     .lookup({
       from: 'employee',
       foreignField: 'employeeId',
       localField: '_id',
       as: 'employee'
     }).project({ '_id':1, name: '$name' }).run()

// Result
[
 { '$match': { _id: 'user123' } },
 {
   '$lookup': {
     from: 'employee',
     foreignField: 'employeeId',
     localField: '_id',
     as: 'employee'
   }
 },
 { '$project': { _id: 1, name: '$name' } }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment