存储架构

mongodb doesn't save all data

微信扫一扫,分享到朋友圈

mongodb doesn't save all data
0

I need to insert some matrix in mongodb,so I wrote simple following code

var MongoClient = require('mongodb').MongoClient;    
var matrisMaker = function(d1,d2){
    var result = new Array();
    for (var i = 0;i < d1;i++){
        result.push(new Array());
        for (var k = 0;k < d2;k++){
            result[i].push(Math.round(Math.random() * 1000000000000));
        }
    }
    return result;
};

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('matris');

    for (var counter = 0;counter < 10000000;counter++){
        var insertObject = {
                'matrisA':matrisMaker(20,20),
                'matrisB':matrisMaker(20,20),
                'resultA':new Object(),
                'resultB':new Object()
        };
        collection.insert(insertObject, function(err, docs) {
            if (err)
                throw err;
        });
        delete insertObject;
        if ((counter % 1000) == 0)
            console.log(counter);
    }
    db.close();
  })

when I see log it printed that too many records inserted,like 50,000,but when I use mongodb to count amount of records,it display less,something near 1,000 records.

>use test;
>db.matris.count();

where is the problem?

Problem courtesy of: Moein Hosseini

Solution

Your asynchronous code is flawed and your db.close()
line executes before your asynchronous insert
commands have all completed. You need to control the flow of your program to A) not have a million concurrent database inserts happening/queued and B) wait until they have all been processed by mongo before closing the connection. Consider a helper library such as async.forEach
to help with this if you don’t want to code it yourself.

Solution courtesy of: Peter Lyons

阅读原文...


微信扫一扫,分享到朋友圈

mongodb doesn't save all data
0

Node.js Recipes

Amazon is opening a new dangerous-goods warehouse after dozens of fulfillment-center worker...

上一篇

Modern Assembly: Using Cobot Arms for Increased Efficiency

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

mongodb doesn't save all data

长按储存图像,分享给朋友