Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript mongoDB获得';未定义';偶然发现_Javascript_Mongodb_Reactjs_Socket.io - Fatal编程技术网

Javascript mongoDB获得';未定义';偶然发现

Javascript mongoDB获得';未定义';偶然发现,javascript,mongodb,reactjs,socket.io,Javascript,Mongodb,Reactjs,Socket.io,我想使用所有 bericht.find({ room: room }).toArray(function(err, docs) { assert.equal(err, null); str2 = str2 + docs.message; 这个函数可以找到,唯一的问题是我一直得到'未定义'。但是我想使用值和socket.emit将值发送到客户端大小,以便所有消息都可以在那里使用。有人能帮我吗?我怎么能做到这一点 consturl='1

我想使用所有

bericht.find({
        room: room
      }).toArray(function(err, docs) {
        assert.equal(err, null);
        str2 = str2 + docs.message;
这个函数可以找到,唯一的问题是我一直得到'未定义'。但是我想使用值和socket.emit将值发送到客户端大小,以便所有消息都可以在那里使用。有人能帮我吗?我怎么能做到这一点

consturl='1〕mongodb://localhost:27017';
io.on('连接',(套接字)=>{
var str2=[];
//数据库名称
const dbName='chatapplication';
const findMessageFromRoom=函数(房间、数据库、回调){
//从某个房间得到信息
const bericht=db.collection('bericht');
//找到一些文件
贝里赫特·芬德({
房间:房间
}).toArray(函数(错误、文档){
assert.equal(err,null);
str2=str2+docs.message;
//回拨(文件);
});
控制台日志(str2);
socket.emit('test1',str2);
};
函数getAllMessagesInRoom(房间){
连接(url,函数(err,客户端){
assert.equal(null,err);
log(“已成功连接到服务器”);
const db=client.db(dbName);
findMessageFromRoom(room、db、function(){
client.close();
});
});
}
)

};
Node.js是异步的,它不会等待数据库查询完成,只需立即记录
str2
变量。那个时候它还并没有定义,所以您会在控制台上看到“undefined”消息

像这样使用它:

bericht.find({
    room: room
}).toArray(function(err, docs) {
    assert.equal(err, null);
    str2 = str2 + docs.message;
    // callback(docs);

    console.log(str2);
    socket.emit('test1', str2);
});