服务器启动时存在koa.js mongoose check集合

时间:2016-06-30 21:15:00

标签: mongodb mongoose koa

我是koa.js的新手,与mongoose一起使用,并且有以下场景:在应用启动时,我想加载一个json文件,如果集合没有&#,则用json的内容填充mongo数据库39; t已经存在使用猫鼬。我创建了一个生成器函数loadMusicJSONIntoDB来处理负载,并将该函数与app.listen一起包装在co块中,以便在服务器启动之前发生。

在下面的代码段中,我可以在连接到mongoose.connection.on(' open' ...)之后使用mongoose的listConnection,该部分已被注释掉。我想在loadMusicJSONIntoDB中使用yield来检查Song集合是否存在。

app.js:

var koa = require('koa');
var co = require('co');
var Song = require('./models/song');

var mongoose = require('mongoose');
// mongoose
var connection = mongoose.connect('localhost/test');
...
// Checking for collection exist like this works
// mongoose.connection.on('open', function () {
//   mongoose.connection.db.listCollections({name: 'songs'})
//     .next(function(err, collinfo) {
//         if (collinfo) {
//           console.log("songs collection exists")
//         }
//     });
// });

function *loadMusicJSONIntoDB() {
  console.log("loadMusicJSONIntoDB");
  var parsedMusicJSON = require('./music.json');
  //console.log(parsedMusicJSON);
  try {

    // QUESTION: I would like to do a yield to wait for the connection
    // to be established?

    // songs = yield mongoose.connection.db.listCollections({name: 'songs'})
    //   .next(function(err, collinfo) {
    //        if (collinfo) {
    //          console.log(collinfo);
    //          console.log("songs collection exists")
    //        }
    //    });

    // Would like to do the following only if the songs collection does not exist
    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 loadMusicJSONIntoDB;
  app.listen(3001, function() { console.log('listening on 3001') });
}).catch(function(err) {
  console.error('Server boot failed:', err, err.stack);
});

song.js

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var SongSchema = new Schema({
  name: String,
  tags: []
});

module.exports = mongoose.model("Song", SongSchema);

1 个答案:

答案 0 :(得分:2)

这是我最终做的事情,在app.listen之前在co块内产生连接。但是我不完全理解我的解决方案是如何工作的,特别是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);
});

http://koajs.com/上,我们举了一个例子,将下一步做中间件的中间件链接在一起,但在我上面的例子中,如果我在没有用()调用它的情况下进行下一步。 即。 songs = yield mongoose.connection.db.listCollections({name:' songs'})。next 然后我明白了 [TypeError:无法读取属性' currentDoc'未定义的]

另一方面, songs = yield mongoose.connection.db.listCollections({name:' songs'})。next()有效。

这是我在mongodb,listCollections上找到的文档,但我仍然不确定读取它的next()行为。 https://docs.mongodb.com/manual/reference/command/listCollections/