I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\e-commer backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
Node.js v18.12.1
db.js
const mongoose = require('mongoose');
const mongoURI = "mongodb+srv://wasif:kingofnoobs#cluster0.fmaocsf.mongodb.net/new"
// const server = 'mongodb://localhost:27017'
// const dbName = 'ecommerceBackend'
mongoose.set("strictQuery", false);
const connectToMongo = () => {
try {
mongoose.createConnection(mongoURI);
console.log("Connected");
} catch (error) {
console.log("Error In Connection");
}
}
module.exports = connectToMongo;
index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 3000
app.use(express.json())
app.use(require('./routes/auth'))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const User = require('../models/User');
router.post('/api/auth', [
body('name').isLength({ min: 3 }),
body('email').isEmail(),
body('password').isLength({ min: 5 }),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const user = User(req.body);
user.save()
res.send(req.body);
})
module.exports = router
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
sorry, posting for the first time that's why
Related
I am following the MongoDB MERN tutorial and when my front-end tries to connect to the DB to pull documents it errors out. I have pulled the official version of their GitHub repo and added my connection information and it works properly with theirs. The only differences I can find is theirs uses mongoose, which the tutorial doesn't reference, and the versions of the packages are older.
Tutorial: https://www.mongodb.com/languages/mern-stack-tutorial
npm version: 9.4.1
Error
$ npm start
> server#1.0.0 start
> node server.js
Server is running on port: 5000
TypeError: Cannot read properties of undefined (reading 'collection')
at D:\MERN\mine\server\routes\record.js:19:6
at Layer.handle [as handle_request] (D:\MERN\mine\server\node_modules\express\lib\router\layer.js:95:5)
at next (D:\MERN\mine\server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\MERN\mine\server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\MERN\mine\server\node_modules\express\lib\router\layer.js:95:5)
at D:\MERN\mine\server\node_modules\express\lib\router\index.js:284:15
at Function.process_params (D:\MERN\mine\server\node_modules\express\lib\router\index.js:346:12)
at next (D:\MERN\mine\server\node_modules\express\lib\router\index.js:280:10)
at Function.handle (D:\MERN\mine\server\node_modules\express\lib\router\index.js:175:3)
at router (D:\MERN\mine\server\node_modules\express\lib\router\index.js:47:12)
See attached below image and code for line 19 of record.js.
https://media.discordapp.net/attachments/1072903958386983022/1072903958974189619/image.png
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
let db_connect = dbo.getDb("employees");
db_connect
.collection("records")
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
Image showing WinMerge comparison of my repo vs GitHub repo.
https://media.discordapp.net/attachments/1072903958386983022/1072903959297146980/image.png?width=1017&height=389
I know that my connection credentials are fine as I have used them with MongoDB Compass and their GitHub repo.
I have added numerous console.log commands in places to try and determine what is being set when the server runs.
Adding console.logs within the connectToServer anonymous function never triggers even though it should occur within server.js on line 14.
server.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
record.js - partial
const express = require("express");
// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();
// This will help us connect to the database
const dbo = require("../db/conn");
// This help convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
let db_connect = dbo.getDb("employees");
db_connect
.collection("records")
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
Note: I did try installing mongoose npm install mongoose on the server and it didn't change the results.
If I modify the conn.js file to use async and await I can get details from the db such as a count of records from employees collection. However, none of the routes work properly for the React frontend, though they don't throw errors either.
Revamped conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let _db;
module.exports = {
connectToServer: async function (callback) {
console.log("test");
try {
await client.connect();
} catch (e) {
console.error(e);
}
_db = client.db("employees");
try {
var count = await _db.collection("records").countDocuments();
console.log(count);
} catch (e) {
console.error(e);
}
if(_db !== undefined){
return true;
}
},
getDb: function () {
return _db;
},
};
connectToServer is asynchronous. That means that the code will continue to execute without waiting for this function to complete.
This function is where the _db value is set. Because of the way your code is executing, you're attempting to access the _db value via getDB() before it has been set. As a result, you get back an undefined value.
You'll need to await the connectToServer function, or provide a fallback inside of getDB to handle the scenario where the DB has not yet been initialized.
Thanks to Jake Haller-Roby I was led down the right path. This had to do with async and await.
However, the GitHub repo from the tutorial doesn't rely upon async and await and works fine. I am going to assume that some newer versions of mongodb or express with nodejs changes how things work.
Here is the code I ended up using.
server.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, async () => {
// perform a database connection when server starts
await dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let _db;
module.exports = {
connectToServer: async function (callback) {
try {
await client.connect();
} catch (e) {
console.error(e);
}
_db = client.db("employees");
return (_db === undefined ? false : true);
},
getDb: function () {
return _db;
},
};
Within the recordRoutes route for getting the list of records I ran into an issue with toArray where it was never returning its promise. After googling for a bit I found there are multiple ways of handling this. Using .then after toArray works as well as storing the results from the toArray in a variable and using an await on its call. Below are the two examples.
.then
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(async function (req, response) {
let db_connect = dbo.getDb();
db_connect
.collection("records")
.find({})
.toArray()
.then((data) => {
console.log(data);
response.json(data);
});
});
try and await
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(async function (req, response) {
let db_connect = dbo.getDb();
try {
var records = await db_connect
.collection("records")
.find({})
.toArray();
response.json(records);
} catch (e) {
console.log("An error occurred pulling the records. " + e);
}
});
const express = require("express")
const app =express()
const mongoose =require("mongoose");
const cors=require('cors');
const FeedbackModel=require('./models/feedback')
app.use(express.json());
app.use(cors);
mongoose.connect("the url no prblm here")
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
the get method is working fine before after i was working on my
frontend it stoped working
app.get("/getfeedback",(req,res)=>{
FeedbackModel.find({},(err,result)=> {
if(err)
{res.json(err)
}
else
{res.json(result)
}
});
})
the app is working fine but if i call for any request the url keep on
loading without any response it just keeps on spinning
app.post("/addfeedback",async(req,res)=>{
const feedback=req.body;
const newFeedback= new FeedbackModel(feedback);
await newFeedback.save();
res.json(feedback);
})
app.listen(3001,()=>{`enter code here`
console.log("Server runs in port 3001");
});
You are using cors package incorrectly.
It has to be called and then it returns whatever value is necessary to the middleware.
Imagine a function that returns a function, the first has to be called to reach the second one.
Try this
app.use(cors());
I am trying to connect to MongoAtlas, however I keep getting
Error: invalid schema, expected mongodb
It seems to be that I can connect, but it cannot get my db from MongoAtlas. My try catch error returns me (node:5964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
.env
PORT = 9055
MONGO_URI =mongodb+srv://<my-db-username>:<my-password>#cluster0.vossd.mongodb.net/<db-name>?
retryWrites=true&w=majority
server.js
require('dotenv').config();
const port = Number.parseInt(process.env.PORT, 10);
const mongoUri = process.env.MONGO_URI;
const {MongoClient} = require('mongodb');
const express = require('express');
const Application = require('./application');
const application = Application();
const Health = require('./health');
const Product = require('./product');
const Cart = require('./cart');
const Order = require('./order');
async function main() {
let db;
try {
db = await MongoClient.connect(mongoUri);
console.log(db)
} catch (err) {
console.log(err);
}
application.use('/health', Health());
application.use('/product', Product(db));
application.use('/cart', Cart(db));
application.use('/order', Order(db));
const server = application.listen(port, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`Shopping website server up and running, listening at http://${host}:${port}`);
});
}
main();
Everything works fine when I'm connected to my local db, so I'm unsure as to what I'm doing incorrectly. Any advice is much appreciated. Thank you!
This cannot read property 'collection' of undefined might be misleading as you have caught the error happening on connection. Hence db is null so if you access collection it will give this error. Below is the sample code from Mongo Atlas.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#test.w7hgn.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true }); // <-- note the option
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Although I am not the first on Stackoverflow not to be able to connect to mongoDB atlas using mongoose, no one seems to have my specific error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-00-shqnc.mongodb.net:27017] on first connect
[MongoNetworkError: connection 5 to
cluster0-shard-00-00-shqnc.mongodb.net:27017 closed]
Here's how my server is set-up:
Keys.js
module.exports = {
mongoURI:
"mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};
Server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true
})
.then(() => {
console.log("MongoDB connected!");
})
.catch(err => {
console.log(err);
});
app.get("/", (req, res) => {
res.send("Hello");
});
//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And this is the code suggested by the MongoDB atlas website to be used:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
But, since I don't want to use mongoClient but rather mongoose, I am having some trouble and I cannot see why the code doesn't work;
EDIT 1: I have managed to connect using the Shell command(Check-out my answer). However, connecting through the app doesn't work and gives a different error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-01-shqnc.mongodb.net:27017] on first connect
[MongoError: bad auth Authentication failed.]
EDIT 2: I made a stupid mistake. I've forgotten to remove <> from the . All is good now.
The problem is that I was trying to connect using my MongoDB Atlas account password instead of the user password. Yes, those are 2 different things.
1. Click on Database Access
2. Edit the current user and modify the password
3. Use that password to connect to MongoDB Atlas
Make sure you have whitelisted your public IP. You can find that by googling "what is my ip".
I am unable to connect to cloud mongodb with the following code. Can anyone please tell me whats wrong with this code?
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ${port}'));
There are multiple steps you should follow to be able to connect Mongo DB so first make sure that you created an account plus connecting to a cluster, while creating it you'll be provided with enough info to create a cluster take your time and read.
after doing that the code is very simple:
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://[ACCOUNT NAME]:[PASSWORD]#cluster0-sxlgp.gcp.mongodb.net/test?retryWrites=true&w=majority", { useNewUrlParser: true }
);
replace ACCOUNTNAME and PASSWORD with info you provided when you created your MongoDB account
This can be found in their documentation try taking your time reading the documentation.
I believe your code looks good the error you are getting TransientTransactionError is temporary please use events to handle your connection result
mongoose
.connect(db, { useNewUrlParser: true })
mongooose.connection.once('open', () => {
console.log('db connection success');
});
mongooose.connection.on('err', (err) => {
console.log('db connection failed');
});