for循环在将文档插入集合时出错

时间:2016-08-23 10:47:25

标签: node.js mongodb

在node.js中我正在编写查询以将文档插入到集合中,但该查询只插入一个文档。在js代码下面是,

app.js

router.post('/creatList', function(req,res){
    console.log(req.body.email);
    var emails = req.body.email;

    if(req.body.wData.wishListType == 'Shared'){
        var findUsers = function(db, callback) {


            var cursor;
            cursor = db.collection('users').find({email: { $in: emails }})

            cursor.toArray(function(err, docs){
                if(err){
                    callback(new Error("Some problem"));
                } else {
                    callback(null,docs);
                } 
            });     
        };

        MongoClient.connect(config.database, function(err, db) {
            assert.equal(null, err);
            findUsers(db, function(err,docs) {
                db.close();
                console.log(docs);
                var inserts_processing = 0;
                for(var key in docs){
                    console.log(key);
                    var ids = docs[key]._id;
                    inserts_processing++;
                    console.log(ids);

                    var insertDocument = function(db, callback) {
                        db.collection('notifications').insertOne({
                            "userId" : ids,
                        },function(err, result) {
                             inserts_processing--;
                            assert.equal(err, null);
                            console.log("Inserted a document into the notifications collection.");
                             if(inserts_processing == 0){
                                db.close();
                                callback();
                            }
                        });
                    };

                    MongoClient.connect(config.database, function(err, db) {
                        assert.equal(null, err);
                        insertDocument(db, function() {
                            db.close();
                        });
                    });
                }
            });
        });     


        } else {
            console.log("other");
        }

    });

在上面的代码中,console.log包含两个id 570dec75cf30bf4c09679deb 56fe44836ce2226431f5388f但实际上它只插入了最后一个。

1 个答案:

答案 0 :(得分:0)

根据您更新的代码,我将尝试以下

router.post('/creatList', function(req,res){
    console.log(req.body.email);
    var emails = req.body.email;

    if(req.body.wData.wishListType == 'Shared'){

        // Open one connection to find users and insert documents
        MongoClient.connect(config.database, function(err, db) {
            assert.equal(null, err);

            if(!err){
                findUsers(db, function(err,docs) {

                    if(!err){
                        insertDocs(db, docs, function(){
                            db.close(); // Close connection

                            console.log("All documents have been inserted");
                            res.status(200).send("All is OK");
                        });
                    }

                });
            });     
        }   

    } else
        console.log("other");

});


function insertDocs(db, docs, callback){
    var inserts_processing = 0; // Will contain the number of inserts pending operation     
    for(var key in docs){
        var ids = docs[key]._id;
        inserts_processing++; // Before writing data, add one to processing inserts

        db.collection('notifications').insertOne({
            "userId" : ids,
        }, function(err, result) {
            inserts_processing--; // One insert have been finished, so remove one

            assert.equal(err, null);
            console.log("Document inserted into the notifications collection.");

            // If all inserts have been finished, call back the function
            if(inserts_processing == 0)
                callback();

        });
    }
} 


function findUsers(db, callback) {
    var cursor;
    cursor = db.collection('users').find({email: { $in: emails }})

    cursor.toArray(function(err, docs){
        if(err)
            callback(new Error("Some problem"));
        else 
            callback(null,docs);
    });     
};
相关问题