koa.js mongoose check collection exists on server start koa.js mongoose check collection exists on server start mongoose mongoose

koa.js mongoose check collection exists on server start


Here is what I ended up doing, yield the connection inside the co block before app.listen. but I don't fully understand how my solution is able to work, specifically this part inside app.js: songs = yield mongoose.connection.db.listCollections({name: 'songs'}).next()

app.js

function *loadMusicJSONIntoDB() {  //console.log("loadMusicJSONIntoDB");  var parsedMusicJSON = require('./music.json');  //console.log(parsedMusicJSON);  try {    songs = yield mongoose.connection.db.listCollections({name: 'songs'}).next()    console.log(songs);    // if the song collection doesn't exist    if (!songs)    {      for (var key in parsedMusicJSON) {        if (parsedMusicJSON.hasOwnProperty(key)) {          console.log(key + " -> " + parsedMusicJSON[key]);          //result = yield Song.findOne({name: key});          //console.log(result);          //if (!result) { // create record          var record = { name: key, tags: parsedMusicJSON[key]};          console.log(record);          yield Song.create(record);          //}        }      }    }  } catch (err) {    console.log(err);  }};co(function*() {  yield mongoose.connect('localhost/test');  yield loadMusicJSONIntoDB;  app.listen(3001, function() { console.log('listening on 3001') });}).catch(function(err) {  console.error('Server boot failed:', err, err.stack);});

On http://koajs.com/, we have the example in chaining together middleware of doing yield next, but in my example above, if I do the next without calling it with (). ie.songs = yield mongoose.connection.db.listCollections({name: 'songs'}).next Then I get[TypeError: Cannot read property 'currentDoc' of undefined]

On the other hand,songs = yield mongoose.connection.db.listCollections({name: 'songs'}).next () works.

Here is the documentation I found on mongodb, listCollections, but I am still unsure of the next() behavior reading it. https://docs.mongodb.com/manual/reference/command/listCollections/