从对象集合返回特定数组 [英] Return specific array from object collection

查看:40
本文介绍了从对象集合返回特定数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我将一些数据放入我的套接字客户端中的代码是:

So I get some data into my socket The code in Client is :

useEffect(() => {  
    
    const socket = io("http://localhost:5000/api/socket");
    
    socket.on("newThought", (thought) => {
      console.log(thought);
    });
    
  }, []); 

然后我服务器中的代码是

And then the code in my server is

connection.once("open", () => {
  console.log("MongoDB database connected");

  console.log("Setting change streams");
  const thoughtChangeStream = connection.collection("phonenumbers").watch();

  thoughtChangeStream.on("change", (change) => {
   
    io.of("/api/socket").emit("newThought", change);

  });
});

当我的电话号码"中的某些内容集合被改变了我得到整个集合的回报.我如何才能只获取从集合中的对象更改的数组?因此,例如,如果集合中唯一更改的服务是 ID 为607deefd13c4ebcbcfa0900a"的服务.那应该是唯一返回的而不是整个集合对象.

When something in my "phonenumbers" collection gets changed I get in return the whole collection . How would I be able to only get the array that got changed from the object in collection? So for example if in the collection the only service that changed is the one with id "607deefd13c4ebcbcfa0900a" that should be the only one returned and not the whole collection object.

推荐答案

watch 方法的 options (second) 参数的 fullDocument 参数可用于获取描述 update 操作对文档的更改的增量:

The fullDocument parameter to the options (second) argument to the watch method can be used to get a delta describing the changes to the document for update operations:

const thoughtChangeStream = connection.collection("phonenumbers").watch([], {
  fullDocument: 'updateLookup'
});

thoughtChangeStream.on("change", (change) => {
   
  io.of("/api/socket").emit("newThought", change);

});

这将返回一个像这样的响应文档,其中 updateDescription 包含被更新修改的字段:

This will then return a response document like this where updateDescription contains the fields that were modified by the update:

{
  _id: {
    _data: '8260931772000000012B022C0100296E5A1004ABFC09CB5798444C8126B1DBABB9859946645F696400646082EA7F05B619F0D586DA440004'
  },
  operationType: 'update',
  clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1620252530 },
  ns: { db: 'yourDatabase', coll: 'yourCollection' },
  documentKey: { _id: 6082ea7f05b619f0d586da44 },
  updateDescription: {
    updatedFields: { updatedField: 'newValue' },
    removedFields: []
  }
}

注意:这仅适用于 update 操作,不适用于 replacedeleteinsert

Note: This will only work for update operations and will not work for replace, delete, insert, etc.

另见:

这篇关于从对象集合返回特定数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆