为什么 MongoDB 中的文本仅在我进行一些服务器更新后才加载?

Why is the text in MongoDB is only loading after I make some server update?

我正在尝试制作一个简单的聊天应用程序,并保存对话的历史记录,以便在用户连接到它时它可以显示在页面上。如果我加载页面,它就不起作用,但是如果我对服务器进行任何更改(比如只按 ctrl + S,这会使 nodemon 重新加载服务器),它会根据需要附加消息。为什么会这样?

//server.js
const mongoose = require('mongoose');
const Msg = require('./models/messages')
const io = require('socket.io')(3000, {
    cors: {
        origin: "*"
    }
})

const mongoDB = 'mongodb+srv://12345678:jonasjonas@cluster0.ifsxq.mongodb.net/message-database?retryWrites=true&w=majority'

mongoose.connect(mongoDB).then(() => console.log('connected'))

const users = {};

io.on('connection', (socket) => {
    console.log('new user');
    Msg.find().then(result => {
        socket.emit('output-message', result);
    })
    
    socket.on('username', myname => {
        users[socket.id] = myname;
        socket.broadcast.emit('user-connected', myname)
    })
    socket.on('send-chat-message', message => {
        const msg = new Msg({message:message, user:users[socket.id]});
        msg.save().then(() => {
            socket.broadcast.emit('chat-message', {message:message, name:users[socket.id]})
        })

    })
})

const socket = io('http://localhost:3000');

var messageContainer = document.getElementById('message-container')
var messageForm = document.getElementById('send-container')

var myname = prompt('Qual é o seu nome?');
appendMessage('You joined')
socket.emit('username', myname);

socket.on('chat-message', data => {
    appendMessage(`${data.name}: ${data.message}`);
})

socket.on('output-message', data => {
    for(let i = 0; i < data.length; i++) appendMessage(`${data[i].user}: ${data[i].message}`);
    console.log(data)
    
})

socket.on('user-connected', myname =>
{appendMessage(`${myname} connected`)}
)

messageForm.addEventListener('submit', e => {

    e.preventDefault();
    const message = document.getElementById('message-input').value;
    socket.emit("send-chat-message", message);
    appendOwnMessage(`You: ${message}`);
    document.getElementById('message-input').value = '';
})

function appendMessage(message) {
    const  a = document.createElement('div');
    const b = a.appendChild(document.createElement('p'))
    b.innerText = message;
    b.setAttribute("class", "received")
    messageContainer.append(a)
}

function appendOwnMessage(message) {
    const  a = document.createElement('div');
    const b = a.appendChild(document.createElement('p'));
    b.innerText = message;
    b.setAttribute("class", "sent")
    messageContainer.append(a)
}
<script defer src='http://localhost:3000/socket.io/socket.io.js'></script>
    <script defer src='script.js'></script>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id='test'></div>
    <div id= 'message-container'></div>
    <div id='test'></div>
    <form id='send-container'>
        <input id="message-input" type='text'>
        <button type='submit' id='send-button'>Send</button>
    </form>

在等待用户名之前注册您的听众。您错过了消息。

socket.on('chat-message', data => {
    appendMessage(`${data.name}: ${data.message}`);
})

socket.on('output-message', data => {
    for(let i = 0; i < data.length; i++) appendMessage(`${data[i].user}: ${data[i].message}`);
    console.log(data)
    
})

socket.on('user-connected', myname =>
{appendMessage(`${myname} connected`)}
)

var myname = prompt('Qual é o seu nome?');
appendMessage('You joined')
socket.emit('username', myname);

您也可以考虑在他们注册用户名后发送消息。

socket.on('username', myname => {
       Msg.find().then(result => {
        socket.emit('output-message', result);
        })
        users[socket.id] = myname;
        socket.broadcast.emit('user-connected', myname)
    })