Reputation: 73
I used MongoDB and wrote a connection So I want to connect the MongoDB database to my project but I still can not understand why it is not connected to the database?And how can I test connection?
I wrote my db.js file like below:
const mongodb = require("mongodb");
const connectionString =
'mongodb+srv://database_user:database_password@server";';
mongodb.connect(
connectionString,
{ useNewUrlParser: true, useUnifiedTopology: true },
function (err, client) {
module.exports = client.db();
const app = require("./app");
app.listen(3000);
}
);
And I used this db.js in Model/Users.js like below:
const usersCollection = require("../db").collection("users");
const validator = require("validator");
let User = function (data) {
this.data = data;
this.errors = [];
};
User.prototype.cleanUp = function () {
if (typeof this.data.username != "string") {
this.data.username == "";
}
if (typeof this.data.email != "string") {
this.data.email == "";
}
if (typeof this.data.password != "string") {
this.data.password == "";
}
// this.data = {
// username: this.data.username.trim().toLowerCase(),
// email: this.data.email.trim().toLowerCase(),
// password: this.data.password,
// };
};
//For bogus Properties
User.prototype.validate = function () {
if (this.data.username == "") {
this.errors.push("You Should insert username");
}
if (
this.data.username != "" &&
!validator.isAlphanumeric(this.data.username)
) {
this.errors.push("You can use Number and characters");
}
if (!validator.isEmail(this.data.email)) {
this.errors.push("You Should insert email");
}
if (this.data.password == "") {
this.errors.push("You Should insert password");
}
if (this.data.password.lenght > 0 && this.data.password.lenght < 12) {
this.errors.push(
"Password must be at least 3 Characters and maximum 12 characters."
);
if (this.data.password.lenght > 100) {
this.data.errors.push("Password In over qualified 100 Characters!!!");
}
if (this.data.username.lenght > 0 && this.data.username.lenght < 3) {
this.data.errors.push(
"username must be at least 3 Characters and maximum 3 characters."
);
}
if (this.data.username.lenght > 30) {
this.data.username.errors,
push("username In over qualified 30 Characters!!!");
}
}
};
User.prototype.register = function () {
//Step #1: Validate User data
this.cleanUp();
this.validate();
if (!this.errors.lenght) {
usersCollection.insertOne(this.data);
}
};
module.exports = User;
When I want to run the code I got an error in collection:
/Users/shamimi/Desktop/js/complex-app/models/User.js:1
const usersCollection = require("../db").collection("users");
Upvotes: 1
Views: 4846
Reputation: 3760
the problem is you're not returning anything from db.js, you're connecting to mongo and starting express.
in my opinion you should separate db connection from express start, cause you're planning to use db from all your models and you wouldn't start the express server everytime. You should also consider creating one connection to the database only.
db.js could look like this:
const client = require("mongodb").MongoClient;
const config = require("../config");
let _db;
function initDb(callback) {
if (_db) {
console.warn("Trying to init DB again!");
return callback(null, _db);
}
client.connect(config.db.connectionString, config.db.connectionOptions, connected);
function connected(err, db) {
if (err) {
return callback(err);
}
console.log("DB initialized - connected to: " + config.db.connectionString.split("@")[1]);
_db = db;
return callback(null, _db);
}
}
function getDb() {
return _db;
}
module.exports = {
getDb,
initDb
};
Then you can use it like:
your main file would look like this:
const initDb = require("./db").initDb;
const getDb = require("./db").getDb;
const app = require("express")();
const port = 3001;
app.use("/", exampleRoute);
initDb(function (err) {
app.listen(port, function (err) {
if (err) {
throw err; //
}
console.log("API Up and running on port " + port);
});
);
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
PS If this is a new app using a recent version of NodeJS you should look into ES6 and more modern ways to create classes, use async/await instead of callbacks
Upvotes: 1
Reputation: 772
Add the .then
and .catch
like I did below and you can see if your connection was successful
mongodb.connect(
connectionString,
{ useNewUrlParser: true, useUnifiedTopology: true },
function (err, client) {
module.exports = client.db();
const app = require("./app");
app.listen(3000);
}
).then(() => console.log("DB Connected!"))
.catch(err => {
console.log(
"Error in DB connection : " + JSON.stringify(err, undefined, 2)
);
});
Upvotes: 0