Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.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
Node.js 如何向MongoDB React.js应用程序添加附加功能?_Node.js_Reactjs_Mongodb_Socket.io - Fatal编程技术网

Node.js 如何向MongoDB React.js应用程序添加附加功能?

Node.js 如何向MongoDB React.js应用程序添加附加功能?,node.js,reactjs,mongodb,socket.io,Node.js,Reactjs,Mongodb,Socket.io,每个人 我正在制作一个应用程序,在那里我需要一个功能性的聊天,以及创建群组和发布任何信息的能力(上传文件、图像、GIF,甚至可能是短视频,等等,有点像Facebook) 我最近成功地为两个人创建了一个功能性聊天室,但仅此而已 我最终选择MongoDB作为我的数据库,但我仍然缺乏技能。不要让我从插座开始 下面是我为聊天 const { Schema, model } = mongoose const ChatSchema = new Schema({ people: [{ type:

每个人

我正在制作一个应用程序,在那里我需要一个功能性的聊天,以及创建群组和发布任何信息的能力(上传文件、图像、GIF,甚至可能是短视频,等等,有点像Facebook)

我最近成功地为两个人创建了一个功能性聊天室,但仅此而已

我最终选择MongoDB作为我的数据库,但我仍然缺乏技能。不要让我从插座开始

下面是我为
聊天

const { Schema, model } = mongoose

const ChatSchema = new Schema({
  people: [{
    type: Schema.Types.ObjectId,
    ref: 'user'
  }],
  messages: [{
    user: {
      type: Schema.Types.ObjectId,
      ref: 'user'
    },
    body: {
      type: String,
    },
    date: {
      type: Date,
      default: Date.now
    },
    isMedia: { type: Boolean },
    media: [{
      name: { type: String },
      type: { type: String },
      src: { type: String },
    }]
  }],
  date: {
    type: Date,
    default: Date.now
  }
})

下面是我的
socket
文件中的一个片段,它处理聊天功能

const socketHolder = (io) =>
  io.on("connection", (socket) => {
    // create chat when the first message is posted

    socket.on("spawnChat", async ({ people, message, userId }) => {
      const chat = new Chat({
        people,
        messages: [
          {
            user: userId,
            body: message,
            date: Date.now(),
          },
        ],
        date: Date.now(),
      });
      await chat.save();
      io.emit("chatSpawned", chat);
    });

    // get the chat state when you return to the route and select a someone to chat with
    socket.on(
      "getInitialChatState",
      async ({ userId, theirId, page, limit }) => {
        let chat;
        let messages = [];
        chat = await Chat.find({ people: [userId, theirId] });
        const startIndex = (await chat[0].messages.length) - limit * page;
        const endIndex = (await chat[0].messages.length) - (page - 1) * limit;
        if (!chat || chat.length < 1)
          chat = await Chat.find({ people: [theirId, userId] });
        if (!chat) return;
        if (endIndex > 0 && startIndex < 0)
          messages = await chat[0].messages.slice(0, endIndex);
        else if (endIndex > 0 && startIndex > 0)
          messages = await chat[0].messages.slice(startIndex, endIndex);
        else if (endIndex < 0 && startIndex < 0) messages = [];
        const hasMoreValue = startIndex < chat[0].messages.length;
        const newChat = {
          people: chat[0].people,
          messages,
          date: chat[0].date,
          _id: chat[0].id,
        };
        io.emit("gotInitialChatState", { newChat, hasMoreValue });
      }
    );

    // send a message in a particular chat
    socket.on("message", async ({ _id, body, userId, isMedia, media }) => {
      try {
        const chat = await Chat.findById(_id);
        let urls = [];
        if (isMedia) {
          for await (const item of media) {
            if (item.type === "gif") {
              await urls.push({
                name: item.name,
                type: item.type,
                src: item.src,
              });
            } else {
              const uploadResponse = await cloudinary.uploader.upload(
                item.res,
                { resource_type: item.type }
              );
              await urls.push({
                name: item.name,
                type: item.type,
                src: uploadResponse.url,
              });
            }
          }
          await chat.messages.push({
            user: userId,
            body,
            date: Date.now(),
            isMedia,
            media: urls,
          });
        } else
          await chat.messages.push({
            user: userId,
            body,
            date: Date.now(),
            isMedia: false,
            media: [],
          });
        await chat.save();
        const message = chat.messages[chat.messages.length - 1];
        io.emit("message", { message });
      } catch (e) {
        console.warn(e);
      }
    });
  }
const socketHolder=(io)=>
io.on(“连接”,“插座)=>{
//发布第一条消息时创建聊天室
socket.on(“spawnChat”,异步({people,message,userId})=>{
const chat=新聊天({
人,
信息:[
{
用户:userId,
正文:信息,
日期:date.now(),
},
],
日期:date.now(),
});
等待聊天。保存();
io.emit(“chatprowned”,chat);
});
//返回路线时获取聊天状态,并选择要聊天的人
插座(
“getInitialChatState”,
异步({userId,theirId,page,limit})=>{
让我们聊聊;
让消息=[];
chat=wait chat.find({people:[userId,theirId]});
const startIndex=(等待聊天[0]。messages.length)-限制*页;
const endIndex=(等待聊天[0]。messages.length)-(第1页)*限制;
如果(!chat | | chat.length<1)
chat=wait chat.find({people:[theirId,userId]});
如果(!chat)返回;
如果(endIndex>0&&startIndex<0)
messages=等待聊天[0]。messages.slice(0,endIndex);
else if(endIndex>0&&startIndex>0)
messages=wait chat[0]。messages.slice(startIndex,endIndex);
else if(endIndex<0&&startIndex<0)消息=[];
const hasMoreValue=startIndex{
试一试{
const chat=wait chat.findById(_id);
让URL=[];
if(isMedia){
等待(介质常数项){
如果(item.type==“gif”){
等待URL.push({
名称:item.name,
类型:item.type,
src:item.src,
});
}否则{
const uploadResponse=wait cloudinary.uploader.upload(
项目1.res,
{资源类型:item.type}
);
等待URL.push({
名称:item.name,
类型:item.type,
src:uploadResponse.url,
});
}
}
等待chat.messages.push({
用户:userId,
身体,
日期:date.now(),
伊斯媒体,
媒体:网址,
});
}否则
等待chat.messages.push({
用户:userId,
身体,
日期:date.now(),
伊斯媒体:错,
媒体:[],
});
等待聊天。保存();
const message=chat.messages[chat.messages.length-1];
io.emit(“message”,{message});
}捕获(e){
控制台。警告(e);
}
});
}
我的问题是:我如何重新设计我的
模式
和/或我的
套接字
,使其对多人完全起作用