MongoDB,保存新记录时覆盖最后一个文档

时间:2016-10-07 15:13:37

标签: node.js mongodb express mongoose

我使用node& amp ;;开发了一个API。 express和mongoDB(3.2.9)(mongooseJS)在mLabs上主持。

当使用沙盒版本时,一切似乎都运行良好,但是当我升级到使用群集时,我总是发现我覆盖了该集合中的最后一个条目。

我不确定这是我的代码还是我需要在mLabs上配置的东西。

连接到服务器:

if (cluster.isMaster) {
// Count the CPU's
const cpuCount = require('os').cpus().length;

// Create workers on each CPU
for (let i = 0; i < cpuCount; i += 1) {
    cluster.fork();
}

// Listen for dying workers
cluster.on('exit', (worker) => {
    // Replace the dead worker
    console.log('Worker ${worker.id} died');
    cluster.fork();
});

} else {
    app.listen(port, () => {
        console.log('Worker '+ port +' running');
    });
}

保存数据

db.name = productData.name;         db.imagePath = productData.imagePath;         db.price = Number(productData.price).toFixed(2);         db.siteId = productData.siteId;         db.url = productData.url;

    db.save((error, product) => {
        if(error) {
            utils.handleError(res, error, 'Error message');
        } else {
            // Add to price history
            historyData.saveNewHistory(product._id, productData.price);

            if(boardId){
                boardData.addProductToBoard(boardId, product.url, product._id, userId, targetPrice, productData.price, res);
            }

            res.status(201).json({
                'status': 201,
                'message': 'Added product successfully',
                'product' : product
            });


        }

    });

我没有收到任何错误消息,因为它可能会过度混淆,id是由MongoDB生成的唯一

我忘了提到这个APP / API托管在AWS Beanstalk上,如果这意味着什么。

1 个答案:

答案 0 :(得分:0)

如果替换

,它是否有效

// Create workers on each CPU for (let i = 0; i < cpuCount; i += 1) { cluster.fork(); }

// Create workers on each CPU //for (let i = 0; i < cpuCount; i += 1) { cluster.fork(); //}

如果确实如此,那么您的应用程序不是线程安全的。升级到群集会使您的应用程序创建更多工作人员,如果他们不能很好地协同工作,可能会导致他们覆盖彼此的数据。注释掉for循环会导致进程只生成一个worker。如果它不起作用,那么我无法帮助你。

相关问题