2

我的 node.js 围绕 foreach 循环处理大量数据,在 mongo 中进行读写。它需要 100% 的 CPU 利用率和大约 1 GB 的内存。有什么建议可以改进吗?

请帮忙谢谢。

代码:

worker.process('bell', (job, done) => {
    Logger.info('Processing job of type ' + job.type + ' id ' + job.id);
    let data = job.data;
    Logger.info(JSON.stringify(data));
    let status;
    if (data.users && Array.isArray(data.users)) {
        if (data.users.length <= 0) {
            Logger.error(new Error('No User List is provided For Notification: '));
            done(new Error('No User List is provided For Notification: '));
        }
        status = 'active';
        NotificationService.findById(data.notifications._id) // change state of notification
            .then((doc) => {
                doc.states = status;
                doc.modified_at = new Date().getTime();
                doc.save();
            }).catch(Logger.error);
        data.users.forEach((user) => {
            UserService.findOne({
                id: user
            }).then((doc) => {
                if (doc && !doc.bell_notifications.includes(data.notifications._id)) {
                    doc.badge++;
                    if (doc.bell_notifications.length == 20) {
                        doc.bell_notifications.pop();
                        console.log('checking pop');
                    }
                    doc.bell_notifications.unshift(data.notifications._id);
                    // Logger.info('Sending Notification to ' + user);
                    console.log('Sending notification to ', user);
                    io.io.to(user).emit('newNotificationCount', doc.badge);
                    doc.save();

                }else{
                    // Logger.info(new Error("User Not found : " + user));
                }

            }).catch(console.error)
        });
        done();
        status = 'success';
    } else {
        status = 'failed';
        done(new Error('notification data is not present in chrome job'))
    }
    NotificationService.findById(data.notifications._id) // change state of notification
        .then((doc) => {
            doc.states = status;
            doc.modified_at = new Date().getTime();
            doc.save();
        }).catch(err => Logger.error(new Error(err)))
});
4

0 回答 0