尝试使用mongoose和async保存到数据库时出现多个错误

我正在尝试使用mongoose将某些内容保存到数据库中。 事情是我需要确保保存完成之前,我在程序中移动并closures连接。 知道保存是在mongooseasynchronous我试着使用此代码:

saveFunction = function(song){ song.save(function(err, userObj){ if(err){ console.log('Error' + err); } else{ console.log('saved successfully:', userObj); } }); }; database.prototype.add= function(newSong){ mongoose.connect(url); var song = new songModel({id : newSong.getId(), title : newSong.getTitle(), artist : newSong.getArtist, genre : newSong.getGenre(), rating : newSong.getRating(), link : newSong.getLink()}); console.log("before async"); async.parallel([function (callback){ saveFunction(song); callback(); }],function(){ mongoose.connection.close(); console.log('closed connection'); }); console.log("after async"); nextFreeId++; }; 

^ songModel是全局定义的。

我尝试了很多不同的方法,并改变了很多东西,但我总是得到和有些错误。 有了这个代码,我得到一个process.nexttick(函数()抛出错误)。 我只是不能得到它的工作。 有人可以告诉我什么是错的或提供工作代码?

我认为最佳的控制台应该是这样的:

 before async saved successfully closed connection after async 

谢谢!

编辑:打开到asynchronous以及其他替代品。 我只想让这个代码以任何可能的方式工作。 我只需要保存/查找/删除某些内容,并且需要等待程序的其余执行,直到完成保存/查找/删除操作。 我越来越绝望,在这个问题上单独上了近一天,在一个紧张shedule 🙁

您需要从保存function中返回一个callback。

 saveFunction = function(song,callback){ song.save(function(err, userObj){ if(err){ console.log('Error' + err); return callback(true,err) } else{ console.log('saved successfully:', userObj); return callback(null); } }); }; 

编辑

从你的评论,你所期望的行为永远不会发生。 你在期待

 console.log("before async"); async.parallel -> do your bits console.log('closed connection'); console.log("after async"); 

但是,这是不会发生的,因为async.parallel是一个asynchronous调用,这意味着在移动到下一个命令之前,执行不会等待它完成。 你看到的行为是

 console.log("before async"); async.parallel -> starts console.log("after async"); async.parallel -> console.log('closed connection'); 

节点正在做第一个日志,启动async.parallel ,然后console.logging“后asynchronous”。 然后当async.parallel到达它的callback函数时,它会打印出“closures的连接”,所以它出现在“之后的asynchronous”之后,因为它是在之后执行的。

你想要执行的任何逻辑依赖于async.parallel的结果必须发生在callback函数中 。 此外,当你想asynchronous运行2个或更多的函数时,使用async.parallel ,然后在完成一个callback后执行callback。 您的解决scheme不需要async.parallel。 你可以用下面的代替:

 saveFunction(song,function(err){ if(err){ //failed to save song } mongoose.connection.close(); //you do not need to do this anyway console.log('closed connection'); nextFreeId++; //anything else you need to do here });