How can I save multiple documents concurrently in Mongoose/Node.js?

后端 未结 13 1938
南笙
南笙 2020-12-07 10:20

At the moment I use save to add a single document. Suppose I have an array of documents that I wish to store as single objects. Is there a way of adding them all with a si

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 10:48

    Add a file called mongoHelper.js

    var MongoClient = require('mongodb').MongoClient;
    
    MongoClient.saveAny = function(data, collection, callback)
    {
        if(data instanceof Array)
        {
            saveRecords(data,collection, callback);
        }
        else
        {
            saveRecord(data,collection, callback);
        }
    }
    
    function saveRecord(data, collection, callback)
    {
        collection.save
        (
            data,
            {w:1},
            function(err, result)
            {
                if(err)
                    throw new Error(err);
                callback(result);
            }
        );
    }
    function saveRecords(data, collection, callback)
    {
        save
        (
            data, 
            collection,
            callback
        );
    }
    function save(data, collection, callback)
    {
        collection.save
        (
            data.pop(),
            {w:1},
            function(err, result)
            {
                if(err)
                {               
                    throw new Error(err);
                }
                if(data.length > 0)
                    save(data, collection, callback);
                else
                    callback(result);
            }
        );
    }
    
    module.exports = MongoClient;
    

    Then in your code change you requires to

    var MongoClient = require("./mongoHelper.js");
    

    Then when it is time to save call (after you have connected and retrieved the collection)

    MongoClient.saveAny(data, collection, function(){db.close();});
    

    You can change the error handling to suit your needs, pass back the error in the callback etc.

提交回复
热议问题