Learning to Keep my Promises with Mongoose.js

I spent quite a while today trying to figure out why my Javascript Promises weren’t working. After much confusion, I finally realized, the problem wasn’t with my Javascript but with my database!

The application I’m working on uses MongoDB, and it uses Mongoose.js to make modeling easier. And, it turns out, Mongoose’s API automatically returns Promises as the results of database queries. This makes sense, seeing as how database queries take time to complete. By returning a promise, Mongoose’s API honors Javascript’s asynchronous conventions, allowing the rest of the program to continue on while Mongoose gathers data from the server.

Except, I didn’t want my application to move on. My server-side code was trying to create a new record, but to do so, it needed the data that Mongoose was busy retrieving. So, it needed to wait. I used Javascript’s .then() convention to chain events, preventing the program from running ahead without the data it needed.

Unfortunately for me, I didn’t realize that Mongoose was doing some of this work for me, and so I spent time implementing Promises on my own. Only after I realized that Mongoose automatically returns promises from its queries was I able to get my code working.

Here’s an example of the kind of code I ended up with:

// retrieve an attribute in order to create a new Record
var attributePromise =
Key.findOne({ myKey })
.then((myKey) => {
return myKey.attribute;
});
// pass the new attribute from attributePromise
attributePromise.then((attribute) => {
// create the new record
let record = new Record({
attribute: attribute
});
// save the new record
record.save(function(err, record) {
if (err) {
console.log(err);
});
}
});
});

Have you worked with MongoDB and Mongoose? What tricks have you learned to successfully handle calls to the database while juggling asynchronous Javascript?

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.