Home > Software design >  I'm trying MongoDB with Mongoose, but it throwing an error
I'm trying MongoDB with Mongoose, but it throwing an error

Time:06-04

I'm new to MERN. I faced an issue while using MongoDB with Mongoose. Genuinely, I have no idea about it. An error like this:

const err = new MongooseError(message);

MongooseError: Operation fruits.insertOne() buffering timed out after 10000ms

Here is my code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/fruitsDB', {useNewUrlParser: true});

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model('Fruit', fruitSchema);

const fruit = new Fruit({
    name: "Banana",
    rating: 7,
    review: "Much loved."
});

fruit.save();

Full form of error in terminal:

C:\Bekhruz's  Coding Journey\Bekhruz's Progress\MongooseApp\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:151
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `fruits.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Bekhruz's  Coding Journey\Bekhruz's Progress\MongooseApp\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:151:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

Node.js v17.7.2

Thanks in advance.

CodePudding user response:

Try adding await at mongoose.connect() function. And handle errors with catch function as shown in this link.

CodePudding user response:

Make a top level async function to wait for the MongoDB to connect

Try/Catch your save() function.

(async () => {
  // put your new code here

  await mongoose.connect(/* URL */, { useNewUrlParser: true });

  //...
  
  try {
    fruit.save();
  } catch (err) {
    console.log('Couldn\'t save fruit!');
  }
});

CodePudding user response:

kindly check if you are connected with your DB.

mongoose.connect(
  process.env.MONGO_URL,
  options
)
.then(()=>console.log('connected'))
.catch(e=>console.log(e));

This shall throw a proper error that can be used for debugging.

  • Related