简体   繁体   English

如何与 MongoDb 同步数据并了解文档是否成功创建/更新

[英]How to sync data with MongoDb and know if a document is created/updated sucessfully

I'm developing a MERN chat app and trying to replicate the feature which WhatsApp provides -> message sent/seen status, so for that I need to check whether the message I/user sent is successfully synced/updated/created in my MongoDB , I know similar functionality can be achieved in AWS Amplify using the event outboxMutationEnqueued which says Dispatched when a local change has been newly staged for synchronization with the cloud , so it works like whenever we are trying to push something to synchronize with the cloud, this event is going to be fired, and once it is finished, outboxMutationProcessed is going to be triggered which says Dispatched when a local change has finished syncrhonization with the cloud and is updated locally .我正在开发一个 MERN 聊天应用程序并尝试复制 WhatsApp 提供的功能 -> 消息发送/查看状态,因此我需要检查我/用户发送的消息是否在我的 MongoDB 中成功同步/更新/创建,我知道在AWS Amplify中可以使用事件outboxMutationEnqueued来实现类似的功能,它说Dispatched when a local change has been newly staged for synchronization with the cloud ,所以它的工作方式就像每当我们试图推送一些东西以与云同步时,这个事件将被解雇,一旦完成,将触发outboxMutationProcessed Dispatched when a local change has finished syncrhonization with the cloud and is updated locally

So we can listen to these events whenever we are trying to send a message, and once our message mutation is processed we are going to receive outboxMutationProcessed , and then we can update the status of the message to sent or single tick or delivered .所以我们可以在尝试发送消息时监听这些事件,一旦我们的消息突变被处理,我们将收到outboxMutationProcessed ,然后我们可以将消息的状态更新为sentsingle tickdelivered

import Amplify, {Hub} from 'aws-amplify';

useEffect(() => {
  const listener = Hub.listen('datastore', async (hubData) => {
    const {event, data} = hubData.payload;
    if (event === 'networkStatus') {
      console.log('User has a network connection: ', data.active);
    }
    if (event === 'outboxMutationProcessed') {
      if (data.model === Message)
        console.log('Mutation has been synced with the cloud: ', data);
        // set the message status to delivered.
    }
  })
  return () => listener();
}, []);

So, the question, do we have something similar in MongoDB ?那么,问题是,我们在MongoDB中是否有类似的东西? I'm currently using React Native, Node, Express, Sockets, Mongoose, MongoDB.我目前正在使用 React Native、Node、Express、Sockets、Mongoose、MongoDB。

Currently, my API end point (for creating a new message and saving in to db):目前,我的 API 端点(用于创建新消息并保存到数据库):

router.post('/create_message', checkAuth, async (req, res) => {
  const {chatRoomId, senderId, text} = req.body;
  try {
    const message = new Message({
      chatRoomId,
      senderId,
      text,
    });
    const result = await message.save();

    return res.status(200).json({
      type: 'success',
      data: result,
    });
  } catch (error) {
    return res.status(422).send({error: `${error.message}`});
  }
});

// SOCKET IMPLEMENTATION FOR REALTIME FEATURE

socket.on('listener', async data => {
  io.to(id).emit('new_message', data);
  const message = new Message({
    chatRoomId: data.roomId,
    senderId: data.senderId,
    text: data.text,
  });
  await message.save();
  // maybe something here...? not sure
});

Maybe an event which we can fire, during the await message.save(...something here...) , and if it is successfully saved in our DB, we can send it to our frontend or using socket?也许我们可以在await message.save(...something here...)期间触发一个事件,如果它成功保存在我们的数据库中,我们可以将它发送到我们的前端或使用套接字?

If anyone could provide an example, it would be really helpful!如果有人可以提供一个例子,那将非常有帮助!

Could you do something like:你能做类似的事情:

schema:架构:

{
from: ObjectId,
to: ObjectId,
 message: String,
delivered: Date,
readBy: []}

app.js应用程序.js

conn = new Mongo("YOUR_CONNECTION_STRING");
db = conn.getDB('chat');

const pipeline = [
  { $match: { 'fullDocument.from': 'johnID...' } },
  { $set: { delivered: new Date() } }
];

const collection = db.collection('messages');
const changeStream = collection.watch(pipeline);
changeStream.on('change', function(change){
if(change.fullDocument.delivered){
  //Notify user of delivery
}
if(change.fullDocument.readBy.includes("otherUserID"){
//notify user of read
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM