Node.js 如何高效地连续查询mongodb数据库
我是Node和MongoDB的新手,我有一个看似简单的请求。我已成功连接到数据库,并使用查询获得所需的结果。现在,我想让这个查询无限期地继续下去,因为我的项目的最终目标是实时绘制数据 我本以为一个简单的“while(true)”循环就足够了,但事实似乎并非如此Node.js 如何高效地连续查询mongodb数据库,node.js,mongodb,Node.js,Mongodb,我是Node和MongoDB的新手,我有一个看似简单的请求。我已成功连接到数据库,并使用查询获得所需的结果。现在,我想让这个查询无限期地继续下去,因为我的项目的最终目标是实时绘制数据 我本以为一个简单的“while(true)”循环就足够了,但事实似乎并非如此 const MongoClient = require('mongodb').MongoClient; // Connection URL const url = 'mongodb://<username>:<pass
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://<username>:<password>@ds157614.mlab.com:57614/flight_data';
// Use connect method to connect to the Server
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("flight_data").collection("data");
while(true)
{
dbo.find().sort({_id: 1}).limit(1).toArray(function(err, result) {
if (err) throw err;
console.log("Temperature: " + result[0].data.temperature);
});
}
db.close();
});
const MongoClient=require('mongodb')。MongoClient;
//连接URL
const url='mongodb://:@ds157614.mlab.com:57614/flight_data';
//使用connect方法连接到服务器
connect(url,{useNewUrlParser:true},函数(err,db){
如果(错误)抛出错误;
var dbo=db.db(“飞行数据”)。收集(“数据”);
while(true)
{
dbo.find().sort({u id:1}).limit(1).toArray(函数(err,result){
如果(错误)抛出错误;
console.log(“温度:+结果[0]。数据。温度”);
});
}
db.close();
});
我发现while循环确实在运行,但出于某种原因,当查询在while循环中时,查询就不会发生。如果删除while循环,代码将正常工作。我只想让它不断地打印重复查询的结果。不断地查询数据库是低效和浪费资源的,而不是使用。它监视集合中的任何更改,然后只进行db调用仅适用于Mongo 3.6+
const MongoClient = require("mongodb").MongoClient;
// Connection URL
const url =
"mongodb://<username>:<password>@ds157614.mlab.com:57614/flight_data";
// Use connect method to connect to the Server
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
const collection = db.collection("data");
const changeStream = collection.watch();
changeStream.on("change", next => {
// process next document
collection
.find()
.sort({ _id: 1 })
.limit(1)
.toArray(function(err, result) {
if (err) throw err;
console.log("Temperature: " + result[0].data.temperature);
});
});
db.close();
});
const MongoClient=require(“mongodb”).MongoClient;
//连接URL
常量url=
“mongodb:/:@ds157614.mlab.com:57614/flight_data”;
//使用connect方法连接到服务器
connect(url,{useNewUrlParser:true},函数(err,db){
如果(错误)抛出错误;
常量集合=数据库集合(“数据”);
const changeStream=collection.watch();
changeStream.on(“更改”,下一步=>{
//处理下一个文档
收集
.find()
.sort({u id:1})
.限额(1)
.toArray(函数(错误、结果){
如果(错误)抛出错误;
console.log(“温度:+结果[0]。数据。温度”);
});
});
db.close();
});
我建议您不要在while循环中不断地查询数据库,而要高效地查看感兴趣的收藏的更新。我尝试了一下,现在发现了一些奇怪的错误。其中一个是MongoError:请求了大多数读取问题,但存储引擎不支持它。
@JessieLSmith您使用的是哪个版本的mongo?变更流需要MongoDB 3.6+。看起来我有3.2.2。node.js驱动程序的最新版本是3.2.3。由于我没有使用mongo shell,我需要想出一个不同的解决方案吗?node.js驱动程序的最新版本是3.2.3
这是什么意思?您一定混淆了node.js驱动程序版本和mongodb服务器版本。转到mongo shell并键入db.version(),结果是您的mongodb版本。我不确定您为什么没有安装mongo shell,因为它默认安装在mongo服务器上。还有,为什么你认为观看db不是你的选择?根据您的要求,我觉得这是最好的选择,而不是不断地查询数据库,这在很多方面都是不好的方法。