Connection Timeout Error while connecting to mongoDB with node js - node.js

i am new to Node.js trying to connect node with Mongo
but getting an Error in console
ongooseTimeoutError: Server selection timed out after 30000 ms
at new MongooseTimeoutError (/home/waqar/Documents/ToDoApp/node_modules/mongoose/lib/error/timeout.js:22:11)
at NativeConnection.Connection.openUri (/home/waqar/Documents/ToDoApp/node_modules/mongoose/lib/connection.js:763
Here is My Code
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to Database
try {
// i have changed connection string just for security purpose
mongoose.connect(
'mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority"',
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
}
);
console.log('Connected');
} catch (err) {
console.log('Caught', err);
}
// schema for toDo app
var toDoSchema = new mongoose.Schema({
item: String
});
// Create TOdo Model
var Todo = mongoose.model('Todo',toDoSchema);
var urlEncodeParser=bodyParser.urlencoded({extended: false});
module.exports = function (app) {
app.get('/todo',function(req,res){
// Get Data From Mongooese and pass it to vi
Todo.find({},function(err,data) {
if (err) throw err;
res.render('todo',{todos:data});
});
});
app.post('/todo',urlEncodeParser,function(req,res){
// Get ata from the view and post it to Mongooese DB
var newTodo = Todo(req.body).save(function(err,data) {
if (err) throw err;
res.json(data);
});
});
app.delete('/todo/:item',function(req,res){
// Delete the requested Item from Mongoo DB
Todo.find(req.item.params.replace(/\-/g," ")).remove(function(err,data) {
res.json(data);
});
});
}

Related

Connecting MongoDB with NodeJS results in "collection is not a function" TypeError

I am new to MongoDB. I am trying to establish a connection between my ExpressJS server and a MongoDB database. This is my code:
const PRIMARY_SERVER = "mongodb://localhost:27017/";
const { MongoClient } = require("mongodb");
const client = new MongoClient(PRIMARY_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function connect() {
try {
await client.connect();
console.log("Connected");
module.exports = client.db("mydb");
const app = require("../app.js");
app.listen(5050);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
connect();
The connection gets established fine but as soon as this function gets called:
router.post("/pushbill", async function (req, res) {
databaseConnection.collection("bills").insertOne(object, function(err, result){
if(err) {
result.status(400).send("Error inserting matches.");
} else {
console.log(`Added a new match with id 0`);
result.status(204).send();
}
});
});
I get this error: "(node:17984) UnhandledPromiseRejectionWarning: TypeError: databaseConnection.collection is not a function".
I've searched for this issue for a few hours now but can't seem to find a solution. I tried several different methods of connecting my database, one of them included this ticket: db.collection is not a function when using MongoClient v3.0 . I am using MongoDB 4.13.0.
It was an issue where the connection to MongoDB kept closing before any operation was made.
I solved this issue by opening connection each time a request gets made, and waiting till the operations are done with a callback or in this case a timeout.
const connDB = async(operations, response) => {
try{
const client = new MongoClient('mongodb ip here', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect().then(function(result){
}).catch(function(err){
throw err;
});
const db = await client.db('my_db');
operations(db);
setTimeout(() => {client.close()}, 1500)
} catch(err){
console.error(err);
response.status(500).send({ message: 'Error connecting or operating the database', error: err});
await client.close();
}
}

Mongoose is returning empty array while fetching data from MongoDb Atlas. Why?

App.js file->Connection is established successfully, but in find() callback,data is empty[]
const express = require('express');
const mongoose = require('mongoose');
const Users = require('./users');
const app = express();
mongoose.connect("mongodb+srv://sanjeev:**pass**#cluster0.ckywrym.mongodb.net?retryWrites=true&w=majority/sanjeevDb",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("connection established successfully"));
Within find callback I am getting empty array in data
Users.find({}, (error, data) => {
if (error)
console.log("Error: ", error);
console.log(data)
});
users.js - defining the schema as same on mongoDb Atlas
const mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
country: String
});
module.exports= mongoose.model('userCollect', userSchema);
enter image description here
you are logging data even when there is error. do this
Users.find({}, (err, data) => {
if (err){
console.log(err);
} else {
console.log(data);
})
or
//with async (recommended)
try {
const users = await Users.find({});
console.log(users);
} catch (err) {
console.log(err);
}

Can .save() Mongoose Schema only one time, next i need to restart node.js server to save it again

i have this problem. First i start Mongoose connecting it to Atlas Db.
dbConfig.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://myMongoDbOnAtlas?retryWrites=true&w=majority";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
module.exports = mongoose;
/db/schema/offices.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const OfficeSchema = new Schema({
// Some Properties
});
const Office = mongoose.model('offices', OfficeSchema);
module.exports = Office;
addOfficeController.js
const Office = require('../db/schema/office');
const mongoose = require('../db/dbConfig');
const addOffice = async (req, res, next) => {
const office = req.body;
let newOffice = new Office(office);
newOffice.save((err, data) => {
if(err){
res.status(400).send(err);
console.log(err);
}else{
res.status(201).send(data);
}
mongoose.connection.close();
})
};
module.exports = {
addOffice
};
Now when i start the Node server my controller works fine and save on db the data, but if i try to do it again the callback is an error: MongooseError: Operation offices.insertOne() buffering timed out after 10000ms
Ok i solved in this way
const mongoose = require('mongoose');
const startDb = () => {
mongoose.connect('myMongoDb#cluster0.hazp8.mongodb.net/db?retryWrites=true";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
}
module.exports = startDb;
I exported a function that starts the connection to db, and after save() I close the connection.

Mongodb-mongoose collections undefined

I am new and practicing Mongoose and Mongodb connection. I successfully connect my database to my local machine and get log confirmations. I am trying get my collection without passing mongoose Schema but I am getting error: TypeError: Cannot read property 'collection' of undefined. I don't know what I am doing wrong.
Here is code:
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const { Schema } = mongoose;
const app = express();
mongoose
.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
var connection = mongoose.connection;
connection.db.collection("bags", function (err, collection) {
collection.find({}).toArray(function (err, data) {
console.log(data); // it will print your collection data
})
});
You're trying to access the DB before the connection is established to MongoDB. ( Connecting to DB is asynchronous code )
Also, Read - https://javascript.info/async-await
mongoose
.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => {
console.log("DB Connected!");
var connection = mongoose.connection;
// run logic once db is connected.
connection.db.collection("bags", function (err, collection) {
collection.find({}).toArray(function (err, data) {
console.log(data); // it will print your collection data
})
});
})
.catch(err => {
console.log(err);
});
Or
mongoose.connection.on('connected', err => { // will trigger connected event when connected to MongoDB
var connection = mongoose.connection;
connection.db.collection("bags", function (err, collection) {
collection.find({}).toArray(function (err, data) {
console.log(data); // it will print your collection data
})
});
});

Why model.find() in mongoose is running before creating the collection?

I have this task for creating a database with mongoose and do some CRUD operations:
First I created my server.js file for creating a server and connecting a database to the server
My problem is when I run my app for the first time the person.find() result is always empty!!
server.js:
const express = require('express');
const mongoose = require('mongoose');
const personRoute = require('./routes/personRoute')
const app = express();
app.use(express.json());
//Connecting the database to the server
mongoose.connect('mongodb+srv://admin:123456#checkpoint.scbz2.mongodb.net/Checkpoint?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
},
err => {
if(err) throw err
else console.log('Database is connected')
}
);
//Using routes with express Router
app.use(personRoute)
//Creating server on port 5000
app.listen(5000 , err => {
if(err) console.log(err)
else console.log('Server is running on port 5000')
})
personSchema.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
//Creating a person schema
const personSchema = new Schema({
name : {type : String, required : true},
age : Number,
favoriteFood : [String]
});
//Exporting the person schema
const person = mongoose.model('person', personSchema);
module.exports = person;
personRoute:
const express = require('express');
const router = express.Router()
const person = require('../model/personSchema');
let arrayOfPeople = require('../arrayOfPeople');
//
let exemple = new person({
name : "Mohamed", age : 26, favoriteFood : ['pasta', 'mloukhia', 'jelbena']
});
exemple.save((err,exemple) => {
if (err) return handleError(err);
else console.log('exemple created and saved: ', exemple);
});
//
person.create(arrayOfPeople,(err, data) => {
if (err) return handleError(err);
else console.log('collection created :', data)
})
//
person.find({name : "Mohamed"}, (err, document) => {
if (err) return handleError(err);
else console.log('Find person by name :', document)
});
module.exports = router;
The problem is in personRoute.js because when I run my app I always get the person.find() result empty actually it always runs before saving the exemple/creating the collection here's an image of my problem:
Image problem
Any help will be always appreciated :)

Resources