mongodb 为什么我的代码不保存用户,但给我的一切都可以响应?

e0bqpujr  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(118)

为什么我的代码不保存用户,但给我的一切ok在响应?它给我一个消息标记为seen. in response当我点击API,但当我检查我的数据库,我看不到任何变化的状态仍然发送,但没有看到,但当我点击它给予我一个响应ok如何解决这个问题?我检查了很多次,它不更新

router.post('/markasread', async (req, res) => {
    const { RoomId, RecieverId } = req.body;

try {
  // Find the recipient's document using their ID
  const recipient = await User.findOne({ _id: RecieverId });

  // Find the message in the recipient's "AllMessages" array using the room ID
  const messageIndex = recipient.AllMessages.findIndex(
    message => message.RoomId === RoomId
  );

  if (messageIndex !== -1) {
    // Update the status of the message to "seen"
    recipient.AllMessages[messageIndex].status = "seen";
    await recipient.save();
  }

  res.status(200).send("Message marked as seen.");
} catch (err) {
  console.log(err);
  res.status(500).send("Error marking message as seen.");
}
  });

这是我的所有消息数组:

AllMessages: {
        type: Array,
        default: [],
    },

这就是我如何在其中创建对象:

router.post('/message', async (req, res) => {
    const { SenderId, message, RoomId, RecieverId, LastMessage, status } = req.body;
    console.log(status)
    try {
        const newMessage = new Message({
            SenderId,
            message,
            RoomId,
            RecieverId,
            timestamp: Date.now(),
        });
        await newMessage.save();

        const date = Date.now();
        const sender = await User.findOne({ _id: SenderId });
        const receiver = await User.findOne({ _id: RecieverId });

        const roomExistsInSender = sender.AllMessages.some(
            (msg) => msg.RoomId === RoomId
        );
        if (!roomExistsInSender) {
            sender.AllMessages.push({
                SenderId,
                RecieverId,
                LastMessage,
                RoomId,
                status,
                date,
            });
            await sender.save();
        }

        const roomExistsInReceiver = receiver.AllMessages.some(
            (msg) => msg.RoomId === RoomId
        );
        if (!roomExistsInReceiver) {
            receiver.AllMessages.push({
                SenderId,
                RecieverId,
                LastMessage,
                RoomId,
                status,
                date,
            });
            await receiver.save();
        }

        await User.updateOne(
            { _id: SenderId, 'AllMessages.RoomId': RoomId },
            {
                $set: {
                    'AllMessages.$.SenderId': SenderId,
                    'AllMessages.$.RecieverId': RecieverId,
                    'AllMessages.$.LastMessage': LastMessage,
                    'AllMessages.$.status': status,
                    'AllMessages.$.date': date,
                },
            },
        );

        await User.updateOne(
            { _id: RecieverId, 'AllMessages.RoomId': RoomId },
            {
                $set: {
                    'AllMessages.$.SenderId': SenderId,
                    'AllMessages.$.RecieverId': RecieverId,
                    'AllMessages.$.LastMessage': LastMessage,
                    'AllMessages.$.status': status,
                    'AllMessages.$.date': date,
                },
            },
        );

        res.status(200).send({ message: "Message saved" });
    } catch (err) {
        console.log(err);
        res.status(422).send(err.message);
    }
});
izj3ouym

izj3ouym1#

尝试使用findOneAndUpdate

router.post('/markasread', async (req, res) => {
  const { RoomId, RecieverId } = req.body;

  try {
    const updatedUser = await User.findOneAndUpdate(
      { _id: RecieverId, 'AllMessages.RoomId': RoomId },
      {
        'AllMessages.$.status': 'seen',
      },
      { new: true }
    );

    if (!updatedUser) return res.status(400).send('User not found.');

    res.status(200).send('Message marked as seen.');
  } catch (err) {
    console.log(err);
    res.status(500).send('Error marking message as seen.');
  }
});

相关问题