changeStream使用nodeJs监视()我的mongodb数据库时出错



错误:"收集方法手表是同步的";。

我在mongo atlas中有一个数据库whatsAppdb,现在想让我的mongodb实时,这样我就可以在mongodb集合中使用changestream,如代码中所示,但在这样做的时候会出现错误";收集方法手表是同步的";如图所示。

在控制台日志"中;Db被连接";如果我不写db.collection("Contact"(语句,则会打印,但添加此语句后应用程序就会崩溃。

/************************************/

[    
const db =mongoose.connection;
db.once("open",function(){
console.log("Db is connected");
});
const msgCollection = db.collection("Contact");
const changeStream = msgCollection.watch();
changeStream.on("change",function(change){
console.log(change);
});
const contactsSchema = {
id:Number,
name : String,
message:String,
time:String
};
const Contact = mongoose.model("Contact", contactsSchema);
app.get("/message",function(req,res){
Contact.find(function(err,findContact){
if(!err){
res.send(findContact);
}else{
res.send(err);
}
});
});
app.post("/",function(req,res){
Contact.create(req.body,function(err,data){
if(!err){
res.send(data);
}else{
res.send("Try Agian.");
}
});
});

app.listen(8000,function(err){
if(!err){
console.log("server started at port 8000");
}else{
console.log(err);
}
});]

错误屏幕截图

只需在数据库连接处添加等待。

await db.once("open", () => {
console.log("DB connected");
});

您的问题是没有确保在数据库连接后调用您的watch函数。连接到mongo是异步的。当您调用找零流时。您可能还没有连接。你应该这样修改你的代码。

db.once("open",function(){
console.log("Db is connected");
const msgCollection = db.collection("Contact");
const changeStream = msgCollection.watch();
changeStream.on("change",function(change){
console.log(change);
});
});

最新更新