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

Multiple errors when trying to save to DB using mongoose and async

本文关键字:DB 错误 保存 mongoose async      更新时间:2024-06-09

我正在尝试使用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
});