skip to Main Content

here is the mongoose version im using "mongoose": "^8.3.2"
and here is the full code

import mongoose from "mongoose";
import User from "./script.js";

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


const run = async()=>{
  try {
    const user = new User({name:"someone", age:55})
    user.save()
    console.log(user)
  } catch (error) {
    console.log(error.message)
  }
}
run()

script.js

import mongoose from "mongoose";

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

export default mongoose.model("User" ,userSchema)

the error

the error

2

Answers


  1. This error occurs due to the fact that there is not any topology description in your Node.js code. In order to solve this issue, you have to set useUnifiedTopology in the connect() function. You can look at the following code in order to achieve this aim:

    const mongoose = require("mongoose");
    mongoose.connect("mongodb://127.0.0.1:27017/your_database", { useUnifiedTopology: true, useNewUrlParser: true });
    

    Besides these, the useNewUrlParser option is also required in Mongoose 6.x or in the later versions.

    Login or Signup to reply.
  2. There is a common Node ipv6 hurdle you need to be aware of when using mongoose. The easiest way to overcome it is to use the 127.0.0.1 system loopback address if your server is running on localhost via ipv4.

    You may also want to await for mongoose to connect so that you can see any connection issues and only execute your run() function if it’s successful like so:

    import mongoose from "mongoose";
    import User from "./script.js";
    
    const run = async()=>{
      try {
        const user = new User({name:"someone", age:55})
        await user.save() //< add await here
        console.log(user)
      } catch (error) {
        console.log(error.message)
      }
    }
    
    mongoose.connect("mongodb://127.0.0.1:27017/appdb")
    .then(async ()=>{
       console.log('Connected to MongoDB');
       await run(); //, add await here
    })
    .catch(err => {
       console.log('Error when connecting: ', err);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search