I
I
Igor Popov2018-06-07 09:21:27
JavaScript
Igor Popov, 2018-06-07 09:21:27

How to display data from a MongoDB collection on the screen?

There is:

// Push при удалении фотографии в админке у пользователя
var sendPhotoRemovePush = function (user) {
    var message = {
        to: user.gcmId,
        notification: {
            title: user.locale == 'en' ? 'Photo deleted (No face)' : 'Фото удалено (Без лица)',
            body: user.locale == 'en' ? 'Upload your photo with a face. Your profile will be deleted with in 24 hours' :
                                 'Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа',
            sound: 'obyjvlenie.mp3'
        }
    };
    sendPush(message);
};

The task is to be able to change the text of messages from the admin panel.
I created a collection in the database with all the messages, made a page in the admin panel, connected the admin panel with the database (you can already change the text through the admin panel and change in the database).
But I don’t know what and how to enter into this .js file instead of these messages, so that when sending the data is taken from the database, I don’t know, but attempts have not yet yielded results.
Here is a simple MongoDB query that gives me the first message:
Notices.findOne({ name: 'sendPhotoRemovePush' }, 'titleEn', function (err, notices) {
        console.log(notices);
});

As in collection:
{
"_id" : ObjectId("5b1055bab772d4a8c93dc0cf"),
"name" : "sendPhotoRemovePush",
"titleEn" : "Photo deleted (No face)",
"titleRu" : "Фото удалено (Без лица)",
"bodyEn" : "Upload your photo with a face. Your profile will be deleted with in 24 hours",
"bodyRu" : "Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа",
"sound" : "obyjvlenie.mp3",
"createdAt" : ISODate("2018-05-31T21:02:39.547Z"),
"updatedAt" : ISODate("2018-06-01T07:09:29.791Z")
}

For a more accurate representation, here is the full version of the message file that needs to be edited:
fcmMessages.js
(function () {
    var path = require('path');
    var config = require('nconf');
    var FCM = require('fcm-push');
    var mongoose = require('mongoose');
    require('../models');
    var User = mongoose.model('User');
    var Notice = mongoose.model('Notice'); // подключаем коллекцию Notice

    config.file({
        file: path.join(__dirname, '../../config/google-services.json')
    });

    var gcmApiKey = config.get('client:0:api_key:0:current_key');
    var fcmSender = new FCM(gcmApiKey);

    var getUser = function (userId, callback) {
        User.findOne({_id: userId}).exec(function (err, user) {
            callback(user);
        });
    };

    var sendPush = function (message) {
        fcmSender.send(message, function (err, response) {
            console.log(message);
            if (err) {
                console.log("sendFcmPush ---> Error:", err);
            } else {
                console.log("sendFcmPush ---> Success: ", response);
            }
        });
    };

    // Push при удалении фотографии в админке у пользователя
    var sendPhotoRemovePush = function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'Photo deleted (No face)' : 'Фото удалено (Без лица)',
                body: user.locale == 'en' ? 'Upload your photo with a face. Your profile will be deleted with in 24 hours' :
                    'Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа',
                sound: 'obyjvlenie.mp3'
            }
        };
        sendPush(message);
    };

    // Push о напоминании что нужно поставить фотографию в профиле
    var sendAboutProfilePhoto = function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'Profile will be deleted' : 'Профиль будет удалён',
                body: user.locale == 'en' ? 'You did not put your photo with a face' : 'Вы не поставили своё фото с лицом',
                sound: 'obyjvlenie.mp3'
            }
        };
        sendPush(message);
    };

    // 1. Push - это находка целей когда происходит запись в БД в hunts
    var sendHunterSignal = function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'Catch or release!' : 'Поймай или отпусти',
                body: user.locale == 'en' ? 'The goal for dating is found!' : 'Найдена цель для знакомства!',
                sound: 'hunterlove.mp3',
                screenState: 'hunter_signal'
            }
        };
        sendPush(message);
    };

    // 2. Заявка на чат кто рядом
    var sendChatInvite = function (userId) {
        getUser(userId, function (user) {
            var message = {
                to: user.gcmId,
                notification: {
                    title: user.locale == 'en' ? 'Application for dating!' : 'Заявка на знакомства',
                    body: user.locale == 'en' ? 'They want to meet you!' : 'С тобой хотят познакомиться!',
                    sound: 'obyjvlenie.mp3',
                    screenState: 'invite_near'
                }
            };
            sendPush(message);
        });
    };

    // 3.1 Принятие заявки
    var sendAcceptInvite = function (userId) {
        getUser(userId, function (user) {
            var message = {
                to: user.gcmId,
                notification: {
                    title: user.locale == 'en' ? 'Rather, in a chat dating!' : 'Скорее в чат знакомств',
                    body: user.locale == 'en' ? 'Your application for dating is accepted!' : 'Твоя заявка на знакомства принята!',
                    sound: 'obyjvlenie.mp3',
                    screenState: 'newnear_message'
                }
            };
            sendPush(message);
        });
    };

    // 3.2 Отказ от чата
    var sendDeclineInvite = function (userId) {
        getUser(userId, function (user) {
            var message = {
                to: user.gcmId,
                notification: {
                    title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                    body: user.locale == 'en' ? 'Your application for dating has been deported!' : 'Твоя заявка на знакомства отклонена!',
                    sound: 'obyjvlenie.mp3',
                    screenState: null
                }
            };
            sendPush(message);
        });
    };
    
    // 4. Новое сообщение в чате с кем были встречи
    var newMessageInChat = function (userId) {
        getUser(userId, function (user) {
            var message = {
                to: user.gcmId,
                notification: {
                    title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                    body: user.locale == 'en' ? 'You have messages from chat!' : 'Тебе сообщения из чата!',
                    sound: 'sms.mp3',
                    screenState: 'new_message'
                }
            };
            sendPush(message);
        });
    }

    // 5. Новое сообщение в чате "Кто рядом"
    var newMessageInChatNear = function (userId) {
        getUser(userId, function (user) {
            var message = {
                to: user.gcmId,
                notification: {
                    title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                    body: user.locale == 'en' ? 'You have messages from chat!' : 'Тебе сообщения из чата!',
                    sound: 'sms.mp3',
                    screenState: 'newnear_message'
                }
            };
            sendPush(message);
        });
    }

    // 6. Создание видеочата
    var createVideoChat = function () {
        var message = {
            to: '/topic/all', // Как отправить всем?
            notification: {
                title:'LoveHunting! / Охота любви',
                body: 'Meet the video chat! / Успей познакомиться в видеочате!',
                sound: 'default',
                screenState: 'video_chat'
            }
        };
        sendPush(message);
    }

    module.exports = {
        sendPhotoRemovePush: sendPhotoRemovePush,
        sendAboutProfilePhoto: sendAboutProfilePhoto,
        sendHunterSignal: sendHunterSignal,
        sendChatInvite: sendChatInvite,
        sendAcceptInvite: sendAcceptInvite,
        sendDeclineInvite: sendDeclineInvite,
        newMessageInChat: newMessageInChat,
        newMessageInChatNear: newMessageInChatNear,
        createVideoChat: createVideoChat,
    };

}).call(this);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Popov, 2018-06-25
@reddy_montano

Solution found:
The function itself:

var sendPhotoRemovePush = function (user) {
   return mongoose.model('Notice')
       .findById(ObjectId("5b1055bab772d4a8c93dc0cf"), function (err, notice) {
           var message = {
               to: user.gcmId,
               notification: {
                   title: user.locale == 'en' ? notice.titleEn : notice.titleRu,
                   body: user.locale == 'en' ? notice.bodyEn : notice.bodyRu,
                   sound: notice.sound
               }
           };
           sendPush(message);
       });
};

C
Coder321, 2018-06-07
@Coder321

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <textarea id="area" cols="100" rows="50"></textarea>
    <script>
        var doc = {
            "_id": "5b1055bab772d4a8c93dc0cf",
            "name": "sendPhotoRemovePush",
            "titleEn": "Photo deleted (No face)",
            "titleRu": "Фото удалено (Без лица)",
            "bodyEn": "Upload your photo with a face. Your profile will be deleted with in 24 hours",
            "bodyRu": "Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа",
            "sound": "obyjvlenie.mp3",
            "createdAt": "2018-05-31T21:02:39.547Z",
            "updatedAt": "2018-06-01T07:09:29.791Z"
        }

        area.value = JSON.stringify(doc, null, 4);
    </script>
</body>

</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question