节点,mongodb和promises有问题

时间:2017-09-09 15:55:49

标签: javascript mongodb callback promise nested

我有使用一系列嵌套回调的工作代码,首先使用find命令检查数据库中是否有预先存在的条目。如果条目存在,则不执行任何操作。如果该条目不存在,请在数据库中插入一个。

此代码运行良好但不提供有意义的错误处理:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/peeps", function(err, db) {
        if(err) {
            if(db) db.close();
            return next();
        }
        var query = { section: req.body.section, year: req.body.year, semester: req.body.semester };
            db.collection("sections").find(query).toArray(function(err, result) {

            if( result.length >= 1  ) {
                db.close();
                if(callback) callback();
            } else {
                var days = [];

                for(var i = 1; i < 6; i++) {

                    if( field['starthour' + i]  != '') {
                        var oneDay = {};
                        oneDay.day = field['day' + i];
                        // more fields being stored here...
                        days.push(oneDay);

                    }
                }

                db.collection("sections").insertOne(
                    { 
                        coursetitle: req.body.course,
                        // more fields being stored here
                        days: days
                    }
                )
                db.close();
                if(callback) callback();
            }
        })
    })

输入promises,一个假定的回调地狱和错误处理修复程序。所以我对promises的第一个问题(我已经搜索并尝试了关键字Mongodb,promise,node和find的每一篇文章)是如何仍然避免嵌套承诺。

以下是我尝试实施Promise策略的一种不同方式:

var MongoClient = require('mongodb').MongoClient;
    MongoClient.connect("mongodb://localhost/peeps")
        .then(function(db) {
            var query = { section: req.body.section, year: req.body.year, semester: req.body.semester };
            db.collection("sections").find(query).toArray(function(err, result) {
                // I am assuming that returns from this callback won't return to the next .then statement...
                // how to avoid nesting promises?
                // If a nested promise is necessary, how do I set it up?  .find does not seem to return a promise... (I've tried)
                if(err) return err; // Where does it go?  probably not to the catch statement like I want it to :-(
                if(result.length >= 1)
                    return {db: db, preexist: true};
                else {
                    return {db: db, preexist: false};
                }
            })
        })
        .then(function(o){
            // o didn't make it here, so db doesn't exist nor preexist, they're undefined
            console.log(o.db + o.preexist)
            // do the insert one if necessary
        })      
        .catch(function(error) {
            console.log(error.message);
        })

所以从本质上讲,我的主要问题是:如何避免嵌套?如果需要嵌套promise,有没有办法将错误返回到最外层的.catch?如果没有指定回调,.find会返回一个promise吗?如果.find可以返回一个promise,那么将结果存储在数组中的正确语法是什么?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

MongoDB就像大多数其他数据库提供程序一样提供了一种检索最新错误的方法。

对于MongoDB,您可以使用Sub Move_Folder() Dim FSO As Object Dim SourcePath As String Dim DestPath As String Dim NameFile as String SourcePath = "C:\Users\Adhy\" '<< Change as needed DestPath = "C:\Users\Mauro\" '<< Change as needed NameFile = "Sheet_1*.xl*" '<< Change as needed Set FSO = CreateObject("scripting.filesystemobject") If FSO.FolderExists(Left(SourcePath,Len(SourcePath)-1)) = False Then MsgBox SourcePath & " doesn't exist" Exit Sub End If 'to move FSO.MoveFile Source:=SourcePath & NameFile , Destination:=DestPath End Sub 来检索错误对象/文档。 Here are the fields you can use from that document.

从更抽象的角度来看,构建承诺的方式取决于数据模型本身,应用程序的逻辑以及您可以安全执行的缓存量。

使用 Promise.all 方法和一组DB操作可以实现链接承诺的方式,而无需多个.then()语句和/或不必要的数据库连接:

db.getLastError()

More information in here: from https://stackoverflow.com/a/45845982/1848744