Error occurs while changeStream watch() my mongodb database using nodeJs

2.3k views Asked by At

error : "Collection method watch is synchronous".

I have a database whatsAppdb in mongo atlas and now want to make my mongodb realtime so for that I uses changestream in mongodb collections as shown in the code but while doing that an error occurs "collection method watch is synchronous" as shown in the image.

In console log "Db is connected" is printed if I don't write the db.collection("Contact") statement but app crashes as soon as add this statement.

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

    [    
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);
    }
});]

error screenshot

2

There are 2 answers

0
user16348540 On

Simply add await at DB connection.

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

0
Chris Matthews On

Your issue is that are not ensuring that your watch function is called after you have a db connection. Connecting to mongo is async. When you are calling your change stream. You might not have a connection yet. You should modify your code like so.

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);
});
});