MongooseError: Operation `tests.findOne()` buffering timed out after 10000ms - node.js

I will be very grateful if you could help me with this issue. Although there are many similar problems, I couldn't find a solution about mine.
Everything is okay, when I'm starting the app- it is connected to the port and the database, but then when I'm using a test post request from insomnia with the url http://localhost:3001/api/testRouter/test
and body {
"testText": "Art",
"testNumber": 1
}. I want a new test to be created and sent to the mongodb atlas, but I'm getting this error:
MongooseError: Operation tests.findOne() buffering timed out after 10000ms
at Timeout. (C:\Users\gabri\OneDrive\Desktop\ip-first\ip-first\server\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (internal/timers.js:551:17)
at processTimers (internal/timers.js:494:7)
This is my db.js file, where I create connection with mongoose:
const mongoose = require('mongoose')
const dotenv = require('dotenv')
dotenv.config()
const connectDB= async()=>
{
try
{
await mongoose.connect(process.env.DATABASE_ACCESS,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
},
()=>
{
console.log("Database connected")
})
}
catch(err)
{
console.log("Error in db connection", err)
}
}
module.exports=connectDB;
This is my test model, which I'm using for testing:
const mongoose = require('mongoose')
const TestSchema = new mongoose.Schema({
testNumber:
{
type:Number,
required: true
},
testText:
{
type: String,
required: true,
trim: true
}
})
const Test = mongoose.model('Test', TestSchema);
module.exports=Test;
This is my test controller, which I'm using it for testing as well:
const Test = require('../models/Test')
exports.testControllerCreate =async(req,res)=>
{
console.log("in router") // it is printed on the console
console.log("body" , req.body) // it is printed on the console
const {testText, testNumber} = req.body;
console.log("check testText", testText) //it is printed on the console
console.log("check testNumber", testNumber) //it is printed on the console
try{
let test= new Test();
test.testText=testText;
test.testNumber=testNumber;
const existingTest = await Test.findOne({testText: testText})
if(existingTest)
{
return res.status(401).json({errorMessage: "Test already exists"})
}
await test.save();
res.status(200).json({successMessage: `Test successfully ${test} created`})
}
catch(err)
{
console.log("err", err)
res.status(500).json({errorMessage: 'Server error'})
}
}
These are my routes:
const express = require('express')
const router=express.Router()
const {testControllerCreate} = require('../controllers/testController')
console.log("router")
router.post('/test', testControllerCreate)
module.exports=router;
And this is my index.js file
const express=require('express')
const app=express()
const cookieParser=require('cookie-parser')
const cors=require('cors')
const connectDB=require('./database/db')
const testRouter = require('./routes/testRoute')
const { connect } = require('./routes/testRoute')
//middlewares
app.use(cors())
app.use(express.json())
app.use(cookieParser())
app.use("/api/testRouter", testRouter)
connectDB();
app.listen(3001, ()=>
{
console.log("running on port 3001 new try")
})
I really hope that someone could help me. I've tried changing the ips in the network access section in the mongodb atlas, checked my url if the password and the username are the same as these from the mongodb atlas, I tried using some extra async await methods, but nothing helped.

Related

Schema DB querying with Mongo Db. I don't understand why but the way I call to push or retrieve data from the db it seems to time out and throw err

I'm very new to MERN so I'm trying to figure out how to use schema correctly within my backend. I'm trying to just make a very simple case here where I just create a new user document in the database. I'm not trying to do anything with auth yet I just want to figure the syntax i guess behind why my code is not communicating correctly with the db.
When I run my backend code it says I successfully am running on port 4000 and that I've connected to my database.
When I check my routes with Postman it seems to time out and return bad request.
Here is my Schema code
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {type:String, required:true},
balance: {type:Number, required:true},
currentLimit: {type:Number, required:true},
maximumLimit: {type: Number, required:true, default:50}
});
module.exports = mongoose.model('user', userSchema);
This is where I make the call to the database in my router function
const express = require('express');
const User = require('../Models/user');
const userInfo = express.Router();
userInfo.route('/userInfo').get(
async function (req, res) {
await User.find().then((err, results) => {
if (err) throw err;
res.json(result);
})
}
);
userInfo.route('/makeUser').post(
async function (req, res) {
const { name, balance, currentLimit, maximumLimit } = req.body;
try {
const user = await User.create({ name, balance, currentLimit, maximumLimit });
res.status(200).json(user);
} catch (error) {
res.status(400).json(error);
console.log('error');
}
}
);
module.exports = userInfo;
This is my connection code
const { MongoClient } = require('mongodb');
const Db = process.env.URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
module.exports = {
connectToDatabase: async function (callback) {
try {
client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
}
This is my index file
const express = require('express');
const cors = require('cors');
require('dotenv').config({path: "./config.env"});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./routing/userInfo'));
const dbo = require("./DB/connection");
app.listen(PORT, ()=>{
console.log(`Server is running on port ${PORT}.`);
dbo.connectToDatabase(function (err){
if (err) console.error(err);
})
})
I feel like I've read so many mongodb schema docs and I do exactly as the docs say but still fail to read or write to/from the db.
You should await client.connect():
module.exports = {
connectToDatabase: async function (callback) {
try {
await client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
};
Also, make sure you are connected to the database before starting the service:
dbo.connectToDatabase(function (err){
if (err) {
console.error(err);
process.exit(1);
}
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
})
Finally, in the get route you are mixing await with then:
userInfo.route('/userInfo').get(async function (req, res) {
const result = await User.find();
res.json(result);
});

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

How do i fix this error i am not using MongoDb Atalas i want to use it in my local machine
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb'
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('DB Connected'))
mongoose.connection.on('error', err => {
console.log(`DB connection error: ${err.message}`)
});
const NewSchema = new mongoose.Schema({
name:String,
age:Number
})
const newModel = new mongoose.model("collection",NewSchema)
const data = newModel({
name:"prajwal",
age:30
})
data.save()
app.listen(3000,()=>{
console.log("listening to the port 3000")
})
This is the error that i got from the code
The save() call should be awaited. Also, looks like you are not connected to the DB, try with:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb';
const NewSchema = new mongoose.Schema({
name: String,
age: Number,
});
const newModel = new mongoose.model('collection', NewSchema);
(async () => {
try {
await mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('DB Connected');
const data = newModel({
name: 'prajwal',
age: 30,
});
await data.save();
} catch (err) {
console.log(`DB connection error: ${err.message}`);
}
})();
app.listen(3000, () => {
console.log('listening to the port 3000');
});

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

I have seen many issues before this in correlation to my issue but all the fixes haven't helped my issue. However, I can now pinpoint the issue. The issue only occurs when I try save a something to the MongoDB with my Message Schema, the connection to the DB is perfectly fine just anything in accordance to the Message Schema breaks it. This is shown as I also have a gridfs & multer setup to save images which works perfectly fine as you will see below and in the console log results. The code is not as clean as I want it to be as I have been trying to fix this for the past few hours.
server.js (entry point)
const express = require('express');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
const app = express();
const Grid = require('gridfs-stream');
const dbConnection = mongoose.createConnection('mongodb://localhost/messages', { useNewUrlParser: true, useUnifiedTopology: true });
let gfs;
dbConnection.once('open', () => {
console.log('Connected to MongoDB');
gfs = Grid(dbConnection.db, mongoose.mongo);
gfs.collection('uploads');
});
dbConnection.on('error', (err) => {
console.log('Error connecting to MongoDB: ' + err);
});
dbConnection.on('disconnected', () => {
console.log('Disconnected from MongoDB');
});
app.set('view engine', 'ejs');
const messageRouter = require('./routes/messages');
app.use('/posts', messageRouter);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(methodOverride('_method'));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
models/message.js
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
message: {
type: String,
required: true
},
author: {
type: String,
required: true
},
date: {
type: Date,
required: true,
default: Date.now()
},
attachment: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'File',
required: false
}
});
module.exports = mongoose.model('Message', messageSchema);
routes/messages.js
/*
Route for: host:port/posts
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const crypto = require('crypto');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const storage = new GridFsStorage({
url: 'mongodb://localhost/messages',
file: (req, file) => {
console.log('storage');
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
const Message = require('../models/message');
router.post('/', upload.single('attachment'), async (req, res) => {
console.log("post recieved");
console.log(req.body.author, req.body.message);
var message = new Message({
message: req.body.message,
author: req.body.author
});
try{
message = await message.save()
console.log("post made");
res.send('Message saved');
} catch (e) {
res.send(e);
console.error(e);
}
})
module.exports = router;
When I input all the info the image gets saved so it is clearly not a connection/auth based issue and the console logs
Server is running on port 3000
Connected to MongoDB
storage
post recieved
Name Message
MongooseError: Operation `messages.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Coding\[REDACTED]\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:151:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
The code had been working perfectly fine a month ago, I picked the project back up, edited a few lines and it has broken

Mongoose, MongoDB/Atlas, Express 404 Not Found

I'm new to MongoDB and I've been troubleshooting this issue for a while now and I simply can't figure it out. Every guide I follow results in a 404 and I'm not sure what I'm doing wrong.
Here's my file structure:
-models
image-upload.js
-routes
recogImages.js
server.js
image-upload.js
const mongoose = require("mongoose");
const imageUploadSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
uploadDate: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("ImageUpload", imageUploadSchema);
recogImages.js
const express = require("express");
const router = express.Router();
const ImageUpload = require("../models/image-upload");
//Getting all records
router.get("/", (req, res) => {
try {
const recogImages = ImageUpload.find();
res.json(recogImages);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
module.exports = router;
server.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const recogImageRouter = require("./routes/recogImages");
const app = express();
const port = 3000;
app.use(express.json());
mongoose.connect(process.env.DATABASE_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// db.on("error", (error) => console.log(error));
db.on("error", console.error.bind(console, "MongoDB connection error"));
db.once("open", () => console.log("Connected to Database"));
app.use("./recog-images", recogImageRouter);
app.listen(port, () => console.log("server started on port: " + port));
Whether I run MongoDB locally or use Atlas, I get a connection to the database but when I query GET http://localhost:3000/recog-images/ I get 404 Not Found Cannot GET /recog-images/.
Try to change this line:
app.use("./recog-images", recogImageRouter);
to:
app.use("/vbox-recog", recogImageRouter);

Mongodb query does not the show the expect result

I am using node and express server to run the mongoDb. For connection and schema I am using mongoose. i successfully connect the database and able to post the data by using postman but problem is it does not show the expected query. Mongodb returns me only the id not the query which is name and description
Here is models
const mongoose = require("mongoose");
const { Schema } = mongoose;
const form = new Schema(
{
name: { type: String },
description: { type: String }
},
{
timestamps: true
}
);
const formSubmit = mongoose.model("formSubmit", form);
module.exports = formSubmit;
This is my express server
const express = require("express");
const port = 5000;
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const formSubmit = require("./models");
const mongoose = require("mongoose");
app.use(cors());
app.use(morgan("dev"));
mongoose
.connect(
"url",
{
useUnifiedTopology: true,
useNewUrlParser: true
}
)
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
//get method
app.get("/show", async (req, res) => {
try {
const entrries = await formSubmit.find();
res.json(entrries);
} catch (error) {
console.log(error);
}
});
//post method
app.post("/post", async (req, res, next) => {
try {
const logs = new formSubmit(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
app.listen(port, () => {
console.log(`Server is running port ${port}`);
});
I think the problem is you don't correctly save the documents to the collection, so when you retrieve them only _id fields display.
To be able to read request body, you need to add express.json() middleware to your server.js.
app.use(express.json());

Resources