J
J
juventino962018-03-25 18:17:00
MongoDB
juventino96, 2018-03-25 18:17:00

Get those users who wrote a message on the Chat?

There are two
Chat schemes

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ChatSchema = new Schema({
    message: String,
    username: String,
    ip_address: String,
    created: { type: String, default: Date.now }
});

module.exports = mongoose.model('Chat', ChatSchema);

Users
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    username : { type: String, required: true, unique: true },
    email: {
        type: String,
        trim: true,
        unique: true,
        required: 'Email address is required',
        validate: [function(email) {
            var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
            return re.test(email)
        }, 'Please fill a valid email address'],
        match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
    },
    avatar: String
});

module.exports = mongoose.model('User', UserSchema);

How to get the data of the user who wrote the message?
var User = require('../models/user.js');
var Chat = require('../models/chat.js');

exports.index = function(req, res) {
    Chat.find(function(err, messages) {
        if (err) {
            console.log(err);
        }
        
        var users = [];

        for (var i = 0, len = messages.length; i < len; i++) {
            var s = User.find({username: messages[i].username}, function(err, user){
                if (err) {
                    console.log(err);
                }

                users.push(user);
            });

            var templateData = {
                users : users,
                messages: messages
            };

            res.render('index.html', templateData);
        }
    });
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iddqd3, 2018-03-29
@iddqd3

make a separate route to which you will pass the user ID, and it will return the necessary information in response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question