[英]socket.io and filtering mongodb by object id
I'm trying to get a document from a mongoDB collection by object id while using Socket.io.我正在尝试在使用 Socket.io 时通过对象 id 从 mongoDB 集合中获取文档。 As
findById()
doesn't work here and i cant do find({ "_id" : _id})
i dont know how to proceed.由于
findById()
在这里不起作用,我不能find({ "_id" : _id})
我不知道如何继续。
This gives me back my entire collection on the client side.这让我在客户端返回了我的整个集合。 But i just want one document by the given _id.
但我只想要一个给定_id 的文档。
The _id arrives on the server side. _id 到达服务器端。 I have checked.
我检查过。
THanks in advance提前致谢
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.