Search code examples
node.jsreactjsmongodbmongoosesocket.io

getting weird mongodb object on client


well as i mentioned in the title when i'm sending message through socket to the server then save it in database mongodb with mongoose, then i returned the the message and send it back in the socket, now when i tried to print it on console in the server right before i send it to the client with socket, i got the object i wanted to send, but when i checked the object i got in the client, then i got diffrent object seems related to mongo probably(pretty sure) and i'm not sure what should i do to fix it.this is what i get in the server right before i send it back to the client this what i get in the client when i recieve new message

const addMessage = async (newMessage) => {
  try {
    if (newMessage.type === 2) {
      const audioBlob = new Buffer.from(newMessage.message).toString("base64");
      newMessage.message = new Binary(audioBlob, Binary.SUBTYPE_BYTE_ARRAY);
    }
    const newMsg = new Message(newMessage);
    await newMsg.save();

   newMsg.message = Buffer.from(newMsg.message.buffer, "base64")

    return newMsg;
  } catch (error) {
    console.log(error);
    errorHandler(error);
  }
};

i expected to get the same object i see in the server so in the client too


Solution

  • well I found the problem, though i'm not sure how to describe it but the problem was here:

    const newMsg = new Message(newMessage);
        await newMsg.save();
    
        newMsg.type === 2
          ? Buffer.from(newMsg.message.buffer, "base64")
          : newMsg.message;
    
        return newMsg;
    

    so i took the newMessage and inserted newMsg.toJSON() to it;

    if (newMessage.type === 2) {
          const audioBlob = new Buffer.from(newMessage.message).toString("base64");
          newMessage.message = new Binary(audioBlob, Binary.SUBTYPE_BYTE_ARRAY);
        }
        const newMsg = new Message(newMessage);
        await newMsg.save();
        newMessage = newMsg.toJSON();
    
        if (newMessage.type === 2) {
          newMessage.message = Buffer.from(newMessage.message.buffer, "base64");
        }
    
        return newMessage;
    

    and now it's working!