HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptMinor

Querying MongoDB for information on a collection of books

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
booksmongodbcollectionqueryingforinformation

Problem

I have this huge chunk of code. Is there any better to write this code, or am I too paranoid that I check every MongoDB query for error?

The logic is here:

  • Bookcollection = collection of books



  • Book = book info



  • Query book collection of the user, if found find the book info for each of the user book collection



  • Create a new collection and insert the book ISBN



  • Send the ISBN to user



How can I improve this code, especially the error-handling?

```
BookCollection.findOne(newBookCollection, function(err, collection){
if (err) {
next(err);
} else {
if (collection) {
collection.update({
$inc: {
quantity: 1
}
}, function(err){
if (err) {
next(err);
} else {
Book.findOne({
isbn: collection.isbn
}, function(err, book){
res.json({
result: 1,
bookInfo: book
});
});
}
});
} else {
Book.findOne({
isbn: isbn
}, function(err, book){
if (err) {
next(err);
} else {
//Book not exist
if (!book) {
var googleBookApiUrl = provider.google.book + isbn + "&key=" + authKey.google.apiKey;

httpsRequest.get(googleBookApiUrl, function(err, data){
if (err) {
next(err);
} else {
if (data.totalItems > 0) {
var volumeInfo = data.items[0].volumeInfo;
var newBook = {};
//Need to fix missing thumbnail

Solution


  • Use Promises. Promises will help with all the indentation, and make your code more clean and understandable in the future (believe me, you'll have no idea of what you were trying to do if you read this code in a couple months)



  • Break up your code in functions. Things like accessing Google Book API shouldn't be in the same place as retrieving data from MongoDB. There should be a clear separation between them; they should have names to help you quickly identify them. Objects are greatly fit for it: they allow you to name a bunch of code (i.e. a function) and call them as necessary.



  • Make the functions return promises. This is extremely important, since it will allow you to create Promises chain.



Besides that, great job. :}

Context

StackExchange Code Review Q#70978, answer score: 2

Revisions (0)

No revisions yet.