Ich bin neu bei koa.js, benutze es mit Mungo, und habe folgendes Szenario: Beim Start der App möchte ich eine JSON-Datei laden, und füllen Sie die Mongo-Datenbank mit der Inhalt des JSons, wenn die Sammlung nicht bereits mit Mungo existiert. Ich habe eine Generator-Funktion loadMusicJSONIntoDB erstellt, um die Last zu verarbeiten, und diese Funktion in einen Co-Block mit app.listen zu verpacken, so dass es vor dem Serverstart passiert.koa.js mongoose check Sammlung existiert auf dem Server Start
In dem Ausschnitt unten, ich bin in der Lage, mongoose listConnection nach dem Einhängen in mongoose.connection.on ('open' ...) zu verwenden, dieser Teil ist auskommentiert. Und ich möchte nach der Existenz der Song-Sammlung suchen, indem ich yield innerhalb von loadMusicJSONIntoDB verwende.
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);