繁体   English   中英

socket.io 和按对象 id 过滤 mongodb

[英]socket.io and filtering mongodb by object id

我正在尝试在使用 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);
    });
  });
});

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

const objectId = new ObjectId(_id)

暂无
暂无

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

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