same issue
Hi @Hamid_Ali,
Welcome to the MongoDB Community forums
It seems that the issue you’re facing could be due to the database not being connected. Could you please ensure the following:
- Confirm that your database is connected, and your code is pointing to the correct URL.
- Check if your
mongoose.connect(...)
code is loading properly. - Verify the structure of your code, especially if you’re running into issues when the
mongoose.connect
code is in a different file. Make sure to require that file in your mainindex.js
file.
Additionally, as per the Mongoose documentation at https://mongoosejs.com/docs/connections.html. The model might be called before the connection is established.
To resolve this, consider using async/await
with connect()
or createConnection()
or use .then()
, as these functions return promises starting from Mongoose 5.
Here’s an example code snippet for your reference:
const dbconnect = async () => {
await connect('<MongoDB_URI>');
console.log("Connected to Database");
}
dbconnect()
.catch((err) => console.error(err))
Make sure to adapt your code accordingly to incorporate these suggestions. I hope it helps!
Best regards,
Kushagra
i was facing the same problem , i didnt found anything on the internet , writing this so it might help someone , my connection string was correct i was using async await. everything was correct still i was getting the error. my problem was that , i was creating mongodb connection in different directory where the model was not present and trying to query in different directory . so it was to able to connect but not able to go to ready state. so i think better keep all your mongoose related file in one place and use only one connection file.