gpt4 book ai didi

node.js - node-mongodb 防止 websocket 数据丢失

转载 作者:可可西里 更新时间:2023-11-01 09:54:05 25 4
gpt4 key购买 nike

我在使用 SocketCluster 的 websocket API 的客户端用于其发布/订阅。

验证后,我通过

接收每秒的 json 数据
SCsocket.on('authenticate', function(){
var channel = SCsocket.subscribe('channel1');
channel.watch(function(data){
console.log(data);
});
});

形式

[
{
"product": "Product1",
"price": "10.0"
},
{
"product": "Product2",
"price": "15.0"
}
]

我不会打印数据,而是将其保存到 mongo 数据库中。

如果某些数据无法上传,我需要某种安全网。回想起来,它允许我将数据从 websocket 上传到 mongo db。

这样做的最佳做法是什么?我希望这个问题不要太宽泛,我是 node 和 mongo db 的新手。

谢谢!

最佳答案

这是一个如何处理数据并将其保存到 Mongo 中的示例。我没有运行 mongo 服务器,因此您必须检查保存是否有效。但是原理是有的。

不确定您所说的安全网是什么意思,但我添加了一项检查以查看数据是否已定义,您应该针对自己的具体情况进行更多检查。

如果您需要任何特定帮助,请告诉我。

SCsocket.on('authenticate', function () {

// subscribe to channel 1
var channel = SCsocket.subscribe('channel1');
channel.watch(function (data) {
// if there is any data
// you should do more specific checks here
if (Object.keys(data).length > 0) {

// connect to mongo
MongoClient.connect(url, function(err, db) {

assert.equal(null, err);

// insert data
insertDocument(data, db, function() {
db.close(); // close db once insert
});
});
} else {
// handle invalid data
console.log('data sent is invalid');
console.log(data);
}
});
});


// insert into mongo
var insertDocument = function (data, db, callback) {

// save into product
db.collection('product').insertOne(
// insert data sent from socket cluster
data, function (err, result) {
assert.equal(err, null);
console.log("Inserted successfully into");
console.log(result); // output result from mongo
callback();
});
};

关于node.js - node-mongodb 防止 websocket 数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com