node.js - nodejs - IF 和 ELSE 都执行

标签 node.js mongodb

必须有一种标准方法来检查文档是否存在,如果不存在则插入。自古以来,这是我们所有人都在做的事情。但那里的例子只显示了一半的例程。我不明白。所以我想出了以下代码。由于某种原因,ifelse 都会执行。该函数不会被调用两次,那么...为什么会发生这种情况?

输出为:

Connected correctly to server
got doc
inserted doc
Disconnected from server successfully

代码是:

// Use connect method to connect to the Server
mongoClient.connect(url, function (err, db) {
    assert.equal(null, err);
    console.log("Connected correctly to server");

    var cursor = db.collection('mycoll').find(mydoc).limit(1);
    // i need 'each' in order to test if doc exists.
    // will execute once because i said limit 1.
    cursor.each(function (err, doc) {
        if (doc != null) {
            console.log("got doc");
        }
        else {
            mydoc.date_submit = new Date();
            db.collection('mycoll').insertOne(mydoc, function (err, r) {
                assert.equal(1, r.insertedCount);
                console.log("inserted doc");
                db.close();
                console.log('Disconnected from server successfully');
            });
        }
    });
});

最佳答案

通过 if (doc != null) 您可以识别循环的结束。这意味着即使您将结果限制为 1,第一次迭代也会返回您查询的文档,而在第二次迭代中光标将为空,并指示这应该是循环/结果的结束。

日志是这样的:

Connected correctly to server
got doc
inserted doc
Disconnected from server successfully

因为您正在 else 语句中执行异步操作。

光标不知道您在查询中的限制。

关于node.js - nodejs - IF 和 ELSE 都执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39832979/

相关文章:

javascript - CloudKitJS 服务器到服务器配置

mysql - nodejs/socket.io 与 node-mysql |安全困惑

javascript - 在 parse.com 中未找到保存 XMLHttpRequest 的 NodeJS 定义

javascript - Mongoose 查询不返回错误

python - 将 Pandas 时间戳插入 Mongodb

node.js - Mongoose 模式方法返回不是一个函数

mongodb - Mongo分页

javascript - Node js/js : Text not appended in file in sequence

javascript - 具有不同超时时间的同步回调

c - mongodb c-api 中的 $exists 查询