实现最简单的解决方案,并且在实际意义上很好地使您的网络应用程序实时https://pusher.com/
这是您在 NodeJS 应用程序中处理推送器的方式
从“推送器”导入推送器
//以下是你在开始时会从推送器中获得的键
// 在您的仪表板中
const pusher = new Pusher({
appId: "<Your app id provided by pusher>",
key: "<Key id provided by pusher>",
secret: "<Secret key given by pusher>",
cluster: "<cluster given by pusher",
useTLS: true
});
现在你想在 MongoDB 中为你的 Collection 设置一个 changeStream
const db = mongoose.collection;
db.once('open', ()=>{
const postCollection = db.collection('posts')//This will be dependent on the collection you want to watch
const changeStream = postCollection.watch()//Make sure the collection name above are acurate
changeStream.on('change', (change)=>{
const post = change.fullDocument;//Change bring back content that change in DB Collection
if (change.operationType === 'insert'){
pusher.triger('<write channel for your pusher>', '<event in this case inser>', {
newPost:post
})
}
})
})
通过该设置,您的推送器和后端现在正在工作,是时候设置前端了
如果您使用 VanillaJS,Pusher 入门有适合您的代码
如果你在这里使用 ReactJS 是下面的代码
import Pusher from 'pusher-js'
useEffect(()=>{
Pusher.logToConsole = true;
var pusher = new Pusher('<Key received from pusher>', {
cluster: '<cluster received from pusher>'
});
var channel = pusher.subscribe('<channel name that you wrote in server');
channel.bind('<event that you wrote in sever',(data)=> {
alert(JSON.stringify(data)); // This will be the data entries coming as soon as they enter DB then you can update your state by using spread operators to maintain what you have and also add new contents
});
//Very important to have a clean-up function to render this once
return ()=>{
pusher.unbind();
pusher.unsubscribe_all();
}
})
现在这样你就拥有了实时的一切