Node.js |MongoDB count():在插入数据之前和之后获取计数 [英] Node.js | MongoDB count(): Getting Count Before and After Inserting Data

查看:55
本文介绍了Node.js |MongoDB count():在插入数据之前和之后获取计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取数据库中的项目计数以确认数据插入成功.

I am trying to get the counts of items in a database to confirm that data insertion is successful.

  1. 插入前获取计数
  2. 插入
  3. 插入后获取计数
  4. Console.log 总结

注意:我知道这可以使用一些简单的函数来实现:

Note: I know this can be implemented using some simple functions:

dbName.equal(insertSize, result.insertedCount)

但是,我是 JavaScript 的新手,我认为我需要实现异步回调,所以我想弄清楚这一点.

However, I am new to javascript and I think I've come across a need to implement asynchronous callbacks, so I wanted to figure this out.

插入函数

var insertMany = function() {

    // get initial count
    var count1 = getDbCount();

    // Insert new 'data'
    MongoClient.connect(url, function(err, db) {
        var col = db.collection(collectionName);
        col.insert(data, {w:1}, function(err,result) {});
        db.close();
    });

    /** This needs to be implemented through next/callback
        after the insert operation  **/
    var count2 = getDbCount(); 

    /** These final console logs should be executed after all
        other operations are completed **/    
    console.log('[Count] Start: ' + count1 + ' | End:' +count2);
    console.log('[Insert] Expected: ' + data.length + ' | Actual: ' + (count2 - count1));

};

获取数据库计数函数

var getDbCount = function() {
    MongoClient.connect(url, function(err, db) {
        if (err) console.log(err);

        var col = db.collection(collectionName);

        col.count({}, function(err, count) {
            if (err) console.log(err);
            db.close();
            console.log('docs count: ' + count);
            // This log works fine
        });

    });

    return count; // this is returning as undefined since this is
                  // executing before the count operation is completed
};

我收到错误,因为返回发生在所需的操作完成之前.

I am getting errors because the returns are occurring before the required operations have completed.

感谢您的帮助.

带有 Promise 的 getCount 函数

作为开始,我已将承诺添加到 getCount 函数中:

I have added the promise to the getCount function as a start:

var getCount = function() {

    var dbCount = 0;

    var promise = new Promise(function(resolve, reject) {

        MongoClient.connect(url, function(err, db) {

            if (err) {
                console.log('Unable to connect to server', err);
            } else {
                console.log('Database connection established:' + dbName);
            }

            // Get the collection
            var col = db.collection(collectionName);

            col.count({}, function(err, count) {
                if (err) console.log(err);
                db.close();
                console.log('docs count: ' + count);
                resolve(null);
                dbCount = count;
            });

        });

    });

    promise.then(function() {
        return dbCount;
    });

};

console.log(getCount());

输出仍然是:不明确的建立数据库连接:testdb文档数:500

The output is still: undefined Database connection established:testdb docs count: 500

then({return count}) 代码仍然在 promise {db.count()} 之前执行.它在数据库操作完成之前返回 undefined.

Then then({return count}) code is still being executed before the promise {db.count()}. It returns undefined before the database operations are completed.

推荐答案

一般来说,您遇到的问题是您希望函数返回时值已经存在.对于异步函数,情况通常并非如此.有大量关于异步处理的信息(不要误认为 Java 中的并行处理).

In general the problem you have is that you expect the value to be already there when your functions return. Well with async functions this is often not the case. There is a huge amount of information about async processing (not to be mistaken with parallel processing like in Java).

我创建了一个适合您情况的示例:

I have created an example which should fit your situation:

https://jsfiddle.net/rh3gx76x/1/

var dummyCount = 5
getCount = function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() { // this would be your db call, counting your documents
          resolve(dummyCount); // dummy for number of documents found
      }, 100 * Math.random());
  });
};

insertMany = function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() { // this would be your db call, writing your documents
          dummyCount += 2;
          resolve();
      }, 100 * Math.random());
  });
};

runIt = function(callback) {
   var count1;
   getCount().then(function(count) {
        console.log("First callback with value ", count);
      count1 = count;
        insertMany().then(function() {
         getCount().then(function(count2){
            console.log("Second callback with value ", count2);
                callback(null, count1, count2);
         });
      })
   })
}

runIt(function(err, count1, count2) {
   console.log("count1: " + count1 + ", count2: " + count2);
});

最后一件事.您可能想查看async"包.这对解决这些问题有很大帮助,提供了大量辅助函数和控制流的东西.

One last thing. You might want to check out the "async" package. This helps a lot with those problems providing a lot of helper functions and control flow stuff.

这篇关于Node.js |MongoDB count():在插入数据之前和之后获取计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆