I am using async.js to run a for loop over a collection. For performance reasons, I want to pass in a database connection into the iterator method, so that it's not opening/closing a db connection each time the iterator runs. I am using mongoose.js for my data models.
The code below gets all the Artists in mongo, and then adds a song for each. My question is, how can I use the same db connection from updateAllArtists in addArtistSong?
function updateAllArtists() {
var db = mongoose.createConnection('localhost/dbname');
var Artist = db.model('Artist', artistSchema);
Artist.find({}, function(err, artists) {
// for each artist, add a song
async.forEach(artists, addArtistSong, function(err) {
});
}
function addArtistSong(artist, cb) {
// THIS IS WHERE I NEED A DB CONNECTION
var Song = db.model('Song', songSchema);
}
Can I extend the iterator signature somehow, like addArtistSong(artist, db, cb)? Then how would I pass this in from the forEach call?
createConnectionand registering your schema models once, at app startup. The connection that Mongoose creates is actually a pool of connections that can be freely shared across your code.