Operation `mytables.insertOne()` buffering timed out after 10000ms - mongodb

I am trying to save data to my database MongoDb atlas by making a post request but getting this error "Operation mytables.insertOne() buffering timed out after 10000ms". I have tried many solution available on internet but none of them is working for me (
Server.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const routesUrls = require('./routes/routes');
const cors = require('cors');
dotenv.config();
mongoose.connect(process.env.DATABASE_ACCESS,{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true},()=>console.log("Datbase Connected"));
app.use(express.json());
app.use(cors());
app.use('/app',routesUrls);
app.listen(3000,()=>{
console.log("server.js");
})
routes.js
const express = require('express');
const router = express.Router();
const signUpTemplateCopy = require('../models/SignUpModels');
router.post('/signup',(req,res)=>{
const signedUpUser = new signUpTemplateCopy({
username: req.body.username,
email: req.body.email,
password: req.body.password,
})
// res.send("Hello");
signedUpUser.save()
.then(data=>{
res.send("success");
})
.catch(error=>{
res.send(error.message);
})
})
module.exports = router
SignUpModels
const mongoose = require('mongoose');
const signUpTemplate = new mongoose.Schema({
username:{
type: String,
required: true,
},
email:{
type: String,
required:true,
},
password:{
type:String,
required:true,
},
date:{
type:Date,
default:Date.now,
}
})
module.exports = mongoose.model('mytable',signUpTemplate);
dot.env
DATABASE_ACCESS = "mongodb+srv://nikhil:tempPass#cluster0.lqfx7.mongodb.net/mytable?retryWrites=true&w=majority"
Any help will be appreciated

https://mongoosejs.com/docs/connections.html#buffering
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.
Try
Start your application only after DB is connected.
mongoose.connect(process.env.DATABASE_ACCESS,{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true},(err) => {
console.log(err);
app.listen(3000,()=> {
console.log("server.js");
})
});

Related

how to use connect-mongo version 4x with express-session. I'm getting errors

I am getting errors while trying to save sessions on MongoDB
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const { connection } = require('mongoose');
app.use(
session({
secret: 'some secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client: connection,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
})
);
Error:
C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126
.db(options.dbName)
^
TypeError: con.db is not a function
at C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126:18
Here is the Solution:
const express = require('express');
const session = require('express-session');
require('dotenv').config();
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const PORT = process.env.PORT || 3001;
const MONGO_URI = process.env.MONGODB;
const app = express();
//connectDB should return the client conn.connection.getClient();
const client = connectDB().then((mClient) => {
app.listen(PORT, () => console.log('Server running...');
return mClient;
}).catch(err => console.log(err));
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(
session({
secret: 'some-secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client,
}),
})
);
app.get('/', (req, res, next) => {
res.send('<h1>Hello World (sessions)</h1>');
});
```

cant get current user with axios get

In my API is the current user (I have logged in with passport) but when I make an Axios get request the data field is empty. I absolutely don't know what to do :(
<script>
import axios from "axios"
export default {
name: 'Home',
components: {
},
data: function() {
return {
user: axios.get('http://127.0.0.1:3000/api/').then(response => this.user = response)
}
},
methods: {
}
}
</script>
Here is the output:
Here is my API:
Edit: Here is my Backend File:
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const cors = require('cors')
const passport = require('passport')
let LocalStrategy = require('passport-local').Strategy;
const session = require('express-session')
var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const port = 3000
app.use(cors({
methods:['GET','POST'],
credentials: true
}))
app.use(express.static('public'))
//Passport setup
app.use(session({
secret: 'test',
resave: false,
saveUninitialized: false,
secure: true
}))
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
const apiRoutes = require('./apiRoutes')
app.use(cors())
app.use('/api', apiRoutes)
// connect to database
mongoose.connect('mongodb+srv://#cluster0.dhsiv.mongodb.net/test?retryWrites=true&w=majority',
{useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log('Erfolgreich connected')
})
app.listen(port, () => {
console.log('server is running on port '+port)
})
module.exports;
I hope someone can help me. Thanks a lot guys :)
i have also change my data and run the axios get in mounted but it doesnt change anything.
Routes:
const { _ } = require('core-js');
const { Mongoose } = require('mongoose');
const { find, where } = require('./models/userModel');
const userModel = require('./models/userModel');
let router = require('express').Router();
const bcrypt = require('bcryptjs')
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
let jwt = require('jsonwebtoken');
const { static } = require('express');
require('./passportConfig')
router.get("/", (req, res) => {
res.json({
user: req.user
});
});

MongoDB: No write concern mode named 'majority a' found in replica set configuration

I am working through a traversy media tutorial and I've come across an error (in the title) that I'm not familiar with. I've been trying to learn about this but I'm still stumped as to why its appearing and where its coming from. Furthermore, I havent found any direct matches for this issue.
Here is the code in question, the catch at the bottom is returning the error.message.
edit: its also worth noting that I am able to successfuly add users to my database. So, it runs through the try block but also the catch ... so thats a big confusing. The only response I am getting on postman is the server error 500 message from the catch block.
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const User = require('../../models/User');
// #route GET api/users
// #desc Test route
// #access Public
router.post(
'/',
[
check('name', 'Name is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 }),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
// see if user exists
if (user) {
return res.status(400).json({
errors: [{ msg: 'User already exists' }],
});
}
// get users gravatar
const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm',
});
user = new User({
name,
email,
avatar,
password,
});
// encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// return jsonwebtoken
return res.send('User registered');
} catch (error) {
console.log(error.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
The User schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
connection configuration:
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log('Connected to MongoDB');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;

MongoDb Atlas: UnhandledPromiseRejectionWarning - MongooseTimeoutError

I am new in mongodb and currently following this article: https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1
I am using mongoDB atlas as a course suggested and also whitelist my IP in it as many answers suggested.
File: .env
ATLAS_URI=mongodb+srv://sagar:<mypass>#cluster0-2gcdi.gcp.mongodb.net/test?retryWrites=true&w=majority
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, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
user.model.js
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;
routes: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;
currently its showing Error in console:
UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms
at new MongooseTimeoutError (C:\Users\sagar\OneDrive\Desktop\nodejs\mern-exercise-tracker\backend\node_modules\mongoose\lib\error\timeout.js:22:11)
I am also testing my api in postman where its showing:
Could not get any response
There was an error connecting to http://localhost:5000/users/add.
Error of my screenshot:

How do you pass Mongoose validation errors to JSON for Postman

I am using the mongoose-unique-validator plugin to validate the username in my schema, and I am using Postman to test my routes. When I test the register route of my app with a username I know has already been registered, Postman will get hung up on the POST request, but the mongoose validation error will be present in my console. My question is, how do I get Postman to display the mongoose validation error message as JSON so I can then use the error message in my app?
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true,
uniqueCaseInsensitive: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
UserSchema.plugin(uniqueValidator, { message: 'Someone already has that username'});
module.exports = User = mongoose.model('users', UserSchema);
Try this out,
`axios.get('/user', (req, res =>{
User user = new User(req.body);
user.save().then(data =>{
req.send(200).data("saved");
}).catch(e =>{
req.send(500).send(e.message);
})
}))`