node.js - Node.js 中的 Mongoose 静默崩溃

标签 node.js mongodb

我正在尝试将大量普通对象插入到 mongodb,但发生了一些非常奇怪的事情。假设我尝试像这样插入 1000 个对象

for (var i = 0; i < 1000; i++) {
     var commentAux = {
       'a': 'test' + i,
       'b': 'https://test.com',
       'c': appUser.id,
       'd': 'test of' + i
     }
     comments.push(commentAux);
}
Comment.collection.insert(comments, function (err, docs) {
   if (err) {
     return res.json({success: false, message: 'Comments Fail'});
   }
}

但是如果我将 1000 更改为 1500,服务器就会挂起。它永远不会抛出异常,也不会发出警告,什么也不会。它只是卡在那里。我一直在阅读,这个文档数量甚至没有接近 mongo 支持的限制数量。

有人遇到同样的问题吗?我在 Windows 中使用 mongo 3.2

最佳答案

如评论中所述,批量最大大小为 1000...因此我实现了自定义 BulkManager 以便在我的 API 中管理大量文档。

所以我的 BulkManager.js 就是这个。

module.exports = function () {
    var instance = {};
    var Promise = require("bluebird");
    var Q = require("q");
    Promise.promisifyAll(instance);

    instance.insert = function (DbModel, items) {
        var arrays = [], size = 1000;

        while (items.length > 0)
            arrays.push(items.splice(0, size));

        return saveItems(DbModel, arrays, arrays.length, 0);
    };

    var deferred = Q.defer();

    function saveItems(DbModel, arrays, amountToProcess, indexToProcess) {
        if (indexToProcess <= (amountToProcess - 1)) {
            var items = arrays[indexToProcess];
            DbModel.collection.insert(items, function (err, docs) {
                if (err) {
                    return deferred.reject({success: false, error: err});
                }

                if (amountToProcess > 1 && indexToProcess < (amountToProcess - 1)) {
                    indexToProcess++;
                    saveItems(DbModel, arrays, amountToProcess, indexToProcess);
                } else {
                    return deferred.resolve({success: true, docs: docs});
                }
            });
        }
        return deferred.promise;
    }
    return instance;
};

在我的 API 中,我这样调用它。

BulkManager.insert(PhotoModel, photos).then(function (response) {
    if (!response.success) {
        return res.json({success: false, message: 'Photos Fail'});
    }
    // do stuff on success
}

关于node.js - Node.js 中的 Mongoose 静默崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509295/

相关文章:

javascript - MongoDB 电影票务系统的数据结构

javascript - Mongoose 不返回空对象的属性

node.js - 使用 Angular $http 请求时,passport req.isAuthenticated 始终返回 false

node.js - 为什么 Node.js Postgres Wiki 示例会在每个 http 请求中插入多条记录?

javascript - 两个窗口之间的 Electron ipcRenderer 消息不起作用

javascript - 如何在 Mongoose 中迭代单个键中的多个值

node.js - 如何部署使用 Redis 的 Meteor 应用程序?

node.js - 为 Vue 应用程序前端和 Node.js 后端配置 nginx

java - Spring Boot 和 Spring Data MongoDB : hiding fields in a ResponseBody

php - Docker 无法安装 MongoDB 扩展