skip to Main Content
const mongoose = require("mongoose")

mongoose.connect("mongodb://localhost:27017/testdb")

const userSchema = new mongoose.Schema({
    name : String,
    age : Number
})

const User = mongoose.model("User", userSchema);

const user1 = new User({name: "Jack", age: 24});
user1.save().then(() => console.log("User Saved"));

I was trying to perform CRUD operations on mongoDB database using mongoose and this error popped up.

2

Answers


  1. Establishing a connection is async operation.
    You need to await for it and only then you’ll be able to run queries.

    await mongoose.connect("mongodb://localhost:27017/testdb")
    
    Login or Signup to reply.
  2. I had the same problem. I successfully got fine after see this answer, thank you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search