Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BerkeleyTrue/7f641ad89ae54b707de0e20bfd80a1c0 to your computer and use it in GitHub Desktop.
Save BerkeleyTrue/7f641ad89ae54b707de0e20bfd80a1c0 to your computer and use it in GitHub Desktop.
// add the custom static method to the Loopback User model
// note the dollar sign here indicatest to the user this function
// returns an Observable
User.getPointsById$ = function getPointsById$(id) {
return Observable.create(observer => {
let isDisposed = false;
// Here we tap into mongodb method
// safe ObjectID creation
// MongoID(id: ObjectID|String) => ObjectID
// MongoDB requires id's to be of type ObjectID
const _id = this.app.dataSources.db.connector.getDefaultIdType()(id);
this.app.dataSources.db.connector
.collection('user')
.aggregate([
{ $match: { _id } },
{ $project: { points: { $size: '$progressTimestamps' } } }
], (err, [ { points = 1 } = {}]) => {
if (isDisposed) { return null; }
if (err) { return observer.onError(err); }
observer.onNext(points);
return observer.onCompleted();
});
return Disposable.create(() => { isDisposed = true; });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment