reddy_montano
@reddy_montano
Лучше чем вчера...

Как вывести данные из коллекции MongoDB на экран?

Есть:
// 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);
};

Задача состоит в том, чтобы можно было из админки менять текст сообщений.

Коллекцию я в базе со всеми сообщениями создал, в админке страничку сделал, связал админку с базой (уже можно менять текст через админку и меняется в базе).

Но вот что и как вписать в этот .js файл вместо этих сообщений, чтобы при отправке данные брались из базы, я не знаю, а попытки пока не дали результатов.

Вот простой запрос в MongoDB, который мне выдает первое сообщение:
Notices.findOne({ name: 'sendPhotoRemovePush' }, 'titleEn', function (err, notices) {
        console.log(notices);
});


Как в коллекции:
{
"_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")
}


Для более точного представления, вот полная версия файла с сообщениями, в котором нужно сделать правки:
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);
  • Вопрос задан
  • 441 просмотр
Решения вопроса 1
reddy_montano
@reddy_montano Автор вопроса
Лучше чем вчера...
Решение найдено:

var ObjectId = mongoose.Types.ObjectId; // объявляем ObjectId


Сама функция :

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);
       });
};
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@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>
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы