gpt4 book ai didi

node.js - Node : does a find query to select n last records need to run asynchronously

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:26 24 4
gpt4 key购买 nike

我是nodejs的新手。我想从 mongo 获取最后 n 条记录,并在(n 个 android)客户端连接时将它们写入套接字。我写了一些代码,当我在我拥有的 vps 上测试它时没问题,但是,在转移到新的 vps 后出现了问题。当第一个客户端连接到套接字时,它不会获取记录。但是,如果第二个客户端连接到套接字,则查找查询将再次运行,并且第一个客户端可以看到相关的发出,但第二个客户端则看不到!

我在 io.emit 命令后添加了一个日志,它会针对每个客户端连接运行。

我还添加了另一个发射,它只发送测试文本,并在客户端连接后立即传递给客户端。

我的代码:

const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);

app.get('/', (req, res) => {
res.send('Chat Server is running on port ......')
});


var mongoose = require('mongoose');
var ChatMessage = require('./chatmessage');
var chatsdb = "mongodb://localhost:27017/chatsdb"
mongoose.connect(chatsdb, {useNewUrlParser: true});
mongoose.connection.on('connected', function () {
console.log('Mongoose connected!')
});
mongoose.connection.on('error', function (err) {
console.log('Mongoose default connection error:' + err);
});


io.on('connection', (socket) => {
let userId = socket.id;

console.log('user ' + userId + ' connected');//it always run
io.emit('connected_message', {"message_text": "ok!" , "user_id":userId});//it always run

ChatMessage.find().sort({created_at:-1}).limit(10).exec(function (err, posts) {
let list_of_messages = [];
for (let i = 0; i < posts.length; i++) {
if (posts[i] != null) {
let message = new ChatMessage({"message_text": posts[i].message_text, "name": posts[i].name , "created_at": posts[i].created_at});
list_of_messages.push(message);
}
}

io.emit('last_fifty_message', list_of_messages);
console.log("list_of_messages:" + list_of_messages); //it always run
});

});


server.listen(50000, () => {
console.log('Node app is running on port 50000')

});

它是 ChatMessage 类:

var mongoose = require('mongoose');


const Schema = mongoose.Schema;
var ChatMessageSchema = new Schema({
name : { type: String, require:true },
message_text : { type: String , require:true },
created_at : { type:Date , default: Date.now },
message_id : { type: Number , autoIncrement:true }
});

ChatMessageSchema.pre('save',function(next){
this.created_at = new Date();
console.log('this.created_at : '+this.created_at)
next();
});


var ChatMessage = mongoose.model('ChatMessage' , ChatMessageSchema);

module.exports = ChatMessage;

我不明白。如果查找记录是一个很长的过程,那么它是如何记录但不发出的,为什么会为已经连接的客户端发出它?

是否需要异步运行?我可以使用 async/await 或回调还是......?

最佳答案

您正在使用io.emitio.emit正在发送到所有连接的客户端

要仅向连接的套接字发送信号,请使用 socket.emit

<小时/>

顺便说一句,你应该检查error是否不为空

关于node.js - Node : does a find query to select n last records need to run asynchronously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57033564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com