Home > Blockchain >  getting weird mongodb object on client
getting weird mongodb object on client

Time:01-07

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

CodePudding user response:

you should always, provide code snippets while asking a question.

Th probable reason for the above problem is, you are printing the console.log(result._docs) and sending to the databse the complete result object. Try sending result._docs to your database as well.

P.S: result is just a variable to which your assigning the data. This variable may be different in your code.

(If this does not work, edit your question and attach code)

CodePudding user response:

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!

  • Related