2
\$\begingroup\$

I have a number of functions that follow the basic pattern below. The intent is to provide a MongoDB implementation for a storage interface in a TypeScript application.

Is there a better way to clean this up so that is is simpler or more readable?

find(collection: string, query: any, sort = {}): Observable<[SyncedObject]> {
    return Observable.create(obs => {
        this.mongoService.connect(this.server, (err, db) => {
            db.collection(collection).find(query).sort(sort).toArray().then(results => {
                obs.next(results);
                db.close();
            });
        })
    })
}

findOne(collection: string, query: any, sort = {}): Observable<SyncedObject> {
    return Observable.create(obs => {
        this.mongoService.connect(this.server, (err, db) => {
            db.collection(collection).find(query).sort(sort).limit(1).next().then(result => {
                obs.next(result);
                db.close();
            });
        })
    })
}

// Several more functions like this....
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.