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

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

Related

Node js - mongodb not responding

Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});

how to use async and await to connect to mongoDB database?

I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});

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

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) => {

why do i keep getting OverwriteModelError?

I get the following error when I start the server:
throw new _mongoose.Error.OverwriteModelError(name);
^ OverwriteModelError: Cannot overwrite User model once compiled.
at new OverwriteModelError (/home/pranav/exercise-tracker/mern-exercise-tracker/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)
my user.model.js file
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
}
},
{
timestamps: true
}
);
const User = mongoose.model("User", userSchema);
module.exports = User;
My users.js
const router = require("express").Router();
let User = require("../models/user.model");
router.route("/").get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
const username = req.body.username;
const newUser = new User({ username });
newUser
.save()
.then(() => res.json("User added!"))
.catch(err => res.status(400).json("Error: " + err));
});
module.exports = router;
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
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");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log('Server is running on port : ' + port);
})
Replace
const User = mongoose.model("User", userSchema);
with
const User = mongoose.models['User'] || mongoose.model("User", userSchema);
When your code is running user.model.js is probably being called again, thus calling the initial definition.
Note the models being used in the OR. That method returns an object containing all defined models. It can also be written as mongoose.models.User.

Resources