尝试使用mongoose和async保存到DB时出现多个错误
Multiple errors when trying to save to DB using mongoose and async
我正在尝试使用mongoose将某些内容保存到数据库中。问题是,在我进入程序并关闭连接之前,我需要确保保存完成。知道保存在猫鼬中是异步的,我尝试使用以下代码:
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(function()throw-err)错误。我就是不能让它工作。有人能告诉我出了什么问题,或者给我提供工作代码吗?
我认为最好的控制台应该是这样的:
before async
saved successfully
closed connection
after async
谢谢!
编辑:对异步的其他替代方案也开放。我只想让这个代码以任何可能的方式工作。我只需要保存/查找一些东西/删除一些东西,它需要等待程序的其余执行,直到保存/查找/删除完成。我变得非常绝望,在一个紧张的计划中独自在这个问题上损失了将近一天:(
您需要从保存函数返回一个回调。
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
是一个异步调用,这意味着执行在进入下一个命令之前不会等待完成。你看到的行为是
console.log("before async");
async.parallel -> starts
console.log("after async");
async.parallel -> console.log('closed connection');
节点正在执行第一个日志,启动async.parallel
,然后在"async之后"执行console.log。然后,当async.parallel
到达其回调函数时,它会打印"关闭的连接",因此它出现在"异步之后"之后,因为它是在之后执行的。
要执行的任何依赖于async.parallel
结果的逻辑都必须发生在回调函数中。此外,当您希望异步运行2个或多个函数,然后在它们全部完成后执行回调时,会使用async.parallel
。您的解决方案不需要async.paralle.您可以将其替换为:
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
});
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我如何修复包含在captcha的addthis中的错误
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- CKFinder 3为所选文件返回错误的URL
- 尝试使用mongoose和async保存到DB时出现多个错误
- Android “SQLite 数据库无法从 /CachedGeoposition.db 加载”错误,尝试从 webvi
- 为什么在编译包含指令的html文本(从db)时出现无限摘要错误
- var db=window.openDatabase&&openDatabase();避免错误的好方法
- MongoDb在db.close()上引发错误
- 从javascript调用DB抛出错误
- PhoneGap sqlLitePlugin DB.事务错误期望令牌')'
- Dynamo DB getiitem与node js抛出错误
- 在php的db连接函数的错误信息中显示js警告