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");
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
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)
);
});
Related
I'm trying to see if the userlookUp in the User.prototype.userExists function is true based on the UserChema.findOne() but for some unknown reason, the block is not being executed if its true. In this case, return this.errors.push('User already exists'), is not being executed.
I have some other error checks in another function, and they work great as they are supposed to (being shown in the browser console) except this one.
Looking for some help.
I appreciate it.
userController.js
const User = require('../models/User');
exports.login = function () {};
exports.logout = function () {};
exports.register = function (req, res) {
let user = new User(req.body);
user.register();
if (user.errors.length) {
res.send(user.errors);
} else {
res.send(user);
res.send('Congrats, there are no errors.');
}
};
exports.home = function (req, res) {
res.send('API up and running!');
};
User.js
const validator = require('validator');
const UserSchema = require('./UserSchema');
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
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 = '';
}
// get rid of any bogus properties
this.data = {
username: this.data.username.trim().toLowerCase(),
email: this.data.email.trim().toLowerCase(),
password: this.data.password,
};
};
User.prototype.validate = function () {
if (this.data.username == '') {
this.errors.push('You must provide a username.');
}
if (
this.data.username != '' &&
!validator.isAlphanumeric(this.data.username)
) {
this.errors.push('Username can only contain letters and numbers.');
}
if (!validator.isEmail(this.data.email)) {
this.errors.push('You must provide a valid email.');
}
if (this.data.password == '') {
this.errors.push('You must provide a password longer than 6 characters.');
}
if (this.data.password.length > 0 && this.data.password.length < 6) {
this.errors.push('The password must be longer than 6 characters.');
}
if (this.data.password.length > 50) {
this.errors.push('The password cannot exceed 50 characters.');
}
if (this.data.username.length < 3 && this.data.username.length > 15) {
this.errors.push('The username must be at least 3 characters.');
}
};
User.prototype.userExists = async function () {
try {
let userLookUp = await UserSchema.findOne({
email: this.data.email,
});
if (userLookUp) {
return this.errors.push('User already exists');
} else {
const avatar = gravatar.url(this.data.email, {
s: '200',
r: 'pg',
d: 'mm',
});
userLookUp = new UserSchema({
username: this.data.username,
email: this.data.email,
password: this.data.password,
avatar: avatar,
});
const salt = await bcrypt.genSalt(10);
userLookUp.password = await bcrypt.hash(this.data.password, salt);
await userLookUp.save();
}
} catch (e) {
console.log('there is a server problem');
}
};
User.prototype.register = function () {
// Step #1: Validate user data
this.cleanUp();
this.validate();
this.userExists();
// Step #2: See if user exists
// Step #3: Get users gravatar
// Step #4: Encrypt the password
// Step #5: Return jsonwebtoken
// Step #6: Only if there are no validation errors
// then save the user data into a database
};
module.exports = User;
In the User.register function you run some functions that are promises (async functions) which are not fulfilled before the User.register function returns.
You can do something like this:
User.prototype.register = async function () {
this.cleanUp();
this.validate();
await this.userExists();
};
...
exports.register = async function (req, res) {
let user = new User(req.body);
await user.register();
if (user.errors.length) {
res.send(user.errors);
} else {
res.send(user);
res.send('Congrats, there are no errors.');
}
};
I know this questions gets asked a lot and I have looked at many similar ones but haven't been able to solve it. But I wrote my code exactly as described in MDN webdocs for async/await but it's not working as expected. Basically I am trying to seed my mongo database for my express.js application.
const Activity = require('./Models/activity');
const mongoose = require('mongoose');
const faker = require('faker');
function dropDB() {
//Check if collections exist. Drop if they do.
mongoose.connect("mongodb://localhost/auth_demo", { useNewUrlParser: true , useUnifiedTopology: true });
var db = mongoose.connection;
db.once('open', (err, res) => {
mongoose.connection.db.listCollections().toArray(function (err, names) {
// console.log(names); // [{ name: 'dbname.myCollection' }]
if (names.length > 1) {
console.log("db connect");
db.dropCollection('users', (err, res) => {
if (err){
console.log(err);
}else {
console.log("DB dropped sucessfully");
}
})
}
else {
console.log("no collections to drop");
}
});
})
}
function createUsers() {
var usersAdded = new Array();
return new Promise(resolve => {
for (let i = 0; i<20; i++) {
User.register( new User(
{
username: faker.internet.userName(),
name: faker.name.firstName() + " " + faker.name.lastName(),
zipcode: faker.address.zipCode(),
friends: []
}
), faker.internet.password(), (err, user) => {
if (err){
console.log(err)
}
else {
usersAdded.push(user);
}
}
)
};
resolve(usersAdded);
});
}
async function main() {
dropDB();
let x = await createUsers();
return x;
}
const returnedVal = main();
returnedVal.then((x) => console.log(x.length));
// module.exports = main;
This is always what prints to the console:
0,
db connect,
DB dropped sucessfully,
As you can see the console.log() in main() runs before createUsers() has finished running. So the users array is still empty even though it should have 20 users.
I'm making a verification system where people link their accounts on two different platforms. I've got the code working, but now I need to check if the code is valid. I'm using .forEach on the json file, yet I keep getting the error:
client.verificationCodes.forEach is not a function
and it crashes.
Here is what the json file looks like:
my json file
Here is my code:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
client.verificationCodes.forEach(vCode => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I appreciate help!
You had a syntax error because .forEach doesn't work on objects but on array and since that client.verificationCodes is an object then you need to use Object.entries to convert that to array of key, value.
I've refactored the block causing this error please use this:
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
which will make your whole code like this:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))
In main.js in server folder,
I have this code,
var DDP = require('ddp');
var DDPlogin = require('ddp-login');
var Job = require('meteor-job');
var ddp = new DDP({
host: "127.0.0.1",
port: 3000,
use_ejson: true
});
Meteor.startup(() => {
var myJobs = JobCollection('myJobQueue');
Job.setDDP(ddp);
ddp.connect(function (err) {
if(err) throw err;
DDPlogin(ddp, function (err, token) {
if (err) throw err;
});
});
myJobs.allow({
admin: function (userId, method, params) {
return true;
}
});
Meteor.publish('allJobs', function () {
return myJobs.find({});
});
myJobs.startJobServer();
var workers = Job.processJobs('myJobQueue', 'sendEmail',
function (job, cb) {
console.log(job.data.text);
job.done();
cb(null);
}
);
And in my main.js in client folder,
I have this code,
var myJobs = JobCollection('myJobQueue');
var jobSub = null;
class App extends Component {
componentDidMount(){
if(jobSub !== null)
jobSub.stop();
jobSub = Meteor.subscribe('allJobs');
var job = new Job(myJobs, 'sendEmail',
{
text: 'bozo#clowns.com'
}
);
job.priority('normal')
.retry({ retries: 5,
wait: 60*1000 }) // 1 minute between attempts
.delay(0) // start immediately
.save();
}
...
render(){
console.log(myJobs.find().fetch());
...
}
}
I am using the vsivsi:meteor-job-collection package.
The problem is that console.log() is not executed.
What is wrong in my step by step installation and usage?
I need to console.log() every minute.