Search code examples
javascriptnode.jsmongodbmongooselocalhost

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


I wanted to create a collection inside of my fruitsDB database and add a document with Mongoose:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27000/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: "Apple",
  rating: 7,
  review: "Pretty solid as a fruit."
})

fruit.save();

I started MongoDB community server with the sudo mongod --port 27000 --dbpath /var/lib/mongo command, then nodemon. When I query the list of existing databases in the Mongo shell with the show dbs command, the new fruitsDB database isn't listed and I get this error message through nodemon:

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

    at Timeout.<anonymous> (/home/work/Documents/programming/projects/html-css-js/fruits-project/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:153:23)

    at listOnTimeout (node:internal/timers:564:17)

    at process.processTimers (node:internal/timers:507:7)

MongoDB version: 4.4.4

Mongoose version: 6.7.2

Node.js version: 18.12.0

nodemon version: 2.0.20

OS: Linux (Fedora 37 Workstation)

I tried running Mongo server on different ports (including 27017). Then looked at other related questions here and on MongoDB forum but none of these solved my problem. How can I solve this problem and add documents to the fruitsDB using Node.js and Mongoose?


Solution

  • If you are following a tutorial, you will likely encounter deprecations. The code below is working for me as of today.

    // require mongoose package
    const mongoose = require('mongoose');
     
    main().catch(err => console.log(err));
     
    async function main() {
      // Use connect method to connect to the server
      await mongoose.connect('mongodb://127.0.0.1:27017/FruitsDB');
     
      const fruitSchema = new mongoose.Schema({
        name: String,
        rating: Number,
        review: String
      });
     
      const Fruit = mongoose.model('Fruit', fruitSchema);
     
      const fruit = new Fruit({
        name: 'Apple',
        rating: 7,
        review: 'Pretty solid as a fruit.'
      });
     
      await fruit.save();