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

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

Related

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);

How to get over path requried error in mongoose

I am trying to make this web page to upload the books and there links but it always show the following error
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
authour: {
type: String,
required: true
},
discription: {
type: String,
},
link: {
type: String,
required: true
}
})
const Book = mongoose.model('books', BookSchema);
module.exports = Book ;
This is the schema I am using but it keeps showing
UnhandledPromiseRejectionWarning:
ValidationError: books validation failed: link: Path `link` is required., authour: Path `authour` is
required., name: Path `name` is required. at
model.Document.invalidate (E:\mystletainn\node_modules\mongoose\lib\document.js:2688:32) a
app.js code that I have been using
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
//const methodOverride = require('method-override')
const books = require('./models/books');
mongoose.connect('mongodb://localhost:27017/books', { useNewUrlParser: true, useUnifiedTopology: true
})
.then(() => {
console.log("MONGO CONNECTION OPEN!!!")
})
.catch(err => {
console.log("OH NO MONGO CONNECTION ERROR!!!!")
console.log(err)
})
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'))
app.use(express.urlencoded({ extended: true }));
//app.use(methodOverride('_method'))
app.get('/', async (req, res) => {
const { name } = req.query;
if (name) {
const book = await books.find({name})
res.render('main', { book, name })
} else {
const book = await books.find({})
res.render('main', { book })
}
})
app.get('/upload', async (req, res) => {
const { name } = req.query;
if (name) {
const book = await books.find({name})
res.render('/', { book, name })
} else {
const book = await books.find({})
res.render('upload',{book})
}
})
app.post('/', async (req, res) => {
const newBook = new books(req.body);
// await newBook.save();
console.log(newBook)
res.redirect(`/`)
})
app.listen(3000, () => {
console.log("LISTENING ON PORT 3000")
})
I have tried to resolve it but it is always giving the same error I am not able to save this to the const newbook.even the console.log shows only the id not the form data
You have to set link.required to false or send it with your request body.
You need to change your post method in something like that,
const newBook = new books({
name:req.body.name,
authour:req.body.author,
discription:req.body.description,
link:req.body.link
})

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {

from nodejs app mongose.save() block and doesn't do anything?

I'm trying to use a very basic MongoDB method is to save a document on a database with mongoose.
1.I installed my MongoDB in centos 7
2.Create a database on the Mongo shell using: use mydatabase and insert a document inside it as normal.
3.Install mongoose and make a connection between my nodejs app and the MongoDB:
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
4. test the connection and all is fine with:
db.once('open', () => {
console.log('DB Connected');
});
Import the model schema as normal:
var { Classe } = require('../DBModels/GoClassDBModels/classes');
try to add new document like this:
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
newClasse.save()
My Model is:
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model('Classes', classSchema);
module.exports = { Classe };
SERVER.JS:
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cookieParser = require('cookie-parser');
const _ = require('lodash');
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log('server is started on 80');
});
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once('open', () => {
console.log('DB Connected');
});
db.on('error', (err) => {
console.log(err);
});
var { Classe } = require('../DBModels/GoClassDBModels/classes');
const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(['lakkini.com']));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
next();
});
app.set('view engine', 'hbs');
app.use(express.static('/home/admin/SMS'));
app.use(express.static('/home/admin/assets'));
app.get('/', (req, res) => {
res.render('SMS/dashboard.hbs');
});
app.get('/classes', (req, res) => {
res.render('SMS/classes.hbs');
});
app.get('/inscription', (req, res) => {
res.render('SMS/inscriptions.hbs');
});
app.post('/saveClasse', (req, res) => {
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
console.log('im gonna save the new class');
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log(response);
});
});
The problem is: nothing happened. No document has been inserted and no errors.
Can you suggest to me, please ?
PS: I'm trying to request from an HTTP server without HTTPS.
will that affect my requests nd block the save to the database?
result:
click to see the picture of the result please
Since the whole file was not given for mongoose connection and where save function is called , assuming you have structured it properly i'm giving my answer.
I was able to do this way,
The schema (same as yours) :
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model("Classes", classSchema);
module.exports = { Classe };
Function to insert:
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("DB Connected");
var newClasse = new Classe({
label: "hello",
level: "level",
});
newClasse.save();
});
UPDATE:
SERVER.JS
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cookieParser = require("cookie-parser");
const _ = require("lodash");
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log("server is started on 80");
});
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once("open", () => {
console.log("DB Connected");
});
db.on("error", (err) => {
console.log(err);
});
var { Classe } = require("./models/Classe");
// const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(["lakkini.com"]));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
"Cache-Control",
"no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"
);
next();
});
app.set("view engine", "hbs");
// app.use(express.static("/home/admin/SMS"));
// app.use(express.static("/home/admin/assets"));
// app.get('/', (req, res) => {
// res.render('SMS/dashboard.hbs');
// });
// app.get('/classes', (req, res) => {
// res.render('SMS/classes.hbs');
// });
// app.get('/inscription', (req, res) => {
// res.render('SMS/inscriptions.hbs');
// });
app.post("/saveClasse", (req, res) => {
var newClasse = new Classe({
label: "hello",
level: "level",
});
console.log("im gonna save the new class");
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log("RESPONSE" + response);
});
});
I found the issue, but I don't understand why that.
the first structure was:
**
DBModel
classes.js
Server
server.js**
the structure right now:
**
DBModel
classes.js
server.js
**
I make out the server from that folder and all working fine...??
why that?

NodeJS Express Mongoose return empty []

I tried to make a MEAN stack app, but my API fails to give my requested data.
server.js file:
const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;
//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');
mongoose.Promise = global.Promise;
mongoose.connect(
dburi,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
).then(
() => {
console.log('Connected to mongoDB');
},
(err) => console.log('Error connecting to mongoDB', err),
{ useNewUrlParser: true }
);
//Express app
const app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
console.log(`running at port ${port}`);
});
Routes file:
const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();
router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);
module.exports = router;
Controller file:
const VolcanoSchema = require('../models/volcano.models');
const getAllVulcanoes = (req, res) => {
VolcanoSchema.find((err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVolcanoes};
Model file
const mongoose = require('mongoose');
const VolcanoSchema = new mongoose.Schema({
Volcano_name:{
type: String,
},
Country:{
type: String,
},
Type:{
type: String,
},
Latitude:{
type: Number,
},
Longtitude:{
type: Number,
},
Elevation:{
type: Number,
},
});
module.exports = mongoose.model('Volcano', VolcanoSchema);
The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this
It would be nice if someone point out what i am doing wrong
EDIT: I switched to postgresql for my database hopefully this will work
You should fix the Controller (VulcanoSchema.find needs an empty object as parameter):
Controller file:
const VulcanoSchema = require('../models/vulcano.models');
const getAllVulcanoes = (req, res) => {
VulcanoSchema.find({}, (err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVulcanoes};

Resources