【问题标题】:socket.io and filtering mongodb by object idsocket.io 和按对象 id 过滤 mongodb
【发布时间】:2020-04-28 13:50:37
【问题描述】:

我正在尝试在使用 Socket.io 时通过对象 id 从 mongoDB 集合中获取文档。 由于findById() 在这里不起作用,我不能这样做find({ "_id" : _id}) 我不知道如何继续。

这让我在客户端返回了我的整个收藏。但我只想要给定 _id 的一份文档。

_id 到达服务器端。我检查过。

提前致谢

io.on('connection', socket => {
  console.log('user arrived');
  socket.emit('chat-message', 'hello-world');
  socket.on('send-chat-id', _id => {
    console.log(_id);
    const chats = db.collection('chats');
    chats.find().toArray(function(error, result) { <------
      if (error) {
        throw error;
      }
      socket.emit('chat-messages', result);
    });
  });
});

【问题讨论】:

    标签: javascript reactjs mongodb mongoose socket.io


    【解决方案1】:

    每当您使用findById() 时,您都需要使用以下行将传入的参数从string(来自UI)转换为ObjectId

    const objectId = new ObjectId(_id)
    

    【讨论】:

      猜你喜欢
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      相关资源
      最近更新 更多