This is my server call to route
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
This is my API route
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
This is my cache route function
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
And this is my API call code
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
When it calls the middle function it hangs my code after clinet.get()
I got the answer, I was making a call back but for forget to add await ,
so this is the updated middleware code
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};
use this code to connect redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});
Related
I don't know what I am doing wrong, however the following is not working.
I have the database connecting however when I try and use the connection it won't let me.
index.js
config = require('./config');
const express = require('express');
const app = express();
const mDB = require('./components/mongodb').connect(config.dbUri);
app.get('/testDB', (req,res) =>{
const user = { name: 'John', age: 30 };
mDB.insertOne(user, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted user: ${result.insertedId}`);
res.send("inserted");
});
});
app.listen(3000, () => {
console.log('App listening on port 3000');
});
./components/mongodb.js
const MongoClient = require('mongodb').MongoClient;
module.exports.connect = (uri) => {
MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
if (err) {
console.error(`MongoDB connection error: ${err}`);
process.exit(1);
}
console.log('Successfully connected to MongoDB');
module.exports.client = client;
});
};
module.exports.insertOne = (collection, document) => {
module.exports.client.db('PodToo').collection(collection).insertOne(document, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted document: ${result.insertedId}`);
});
};
I get the Successfully connected to MongoDB
But then when I try and use it I am receiving
TypeError: Cannot read properties of undefined (reading 'insertOne')
In the danger of stating the obvious: You are missing the first argument to your insertOne function, the collection name.
Did you mean
mDB.insertOne('users', user, ...
?
I am seeing my mongoose pool seemingly close before it inserts data as I am getting this error when making a call to my mongoose db in my cloud cluster
MongoRuntimeError: Connection pool closed
but I am awaiting all of the calls? so I'm unsure why I'm seeing this issue, maybe it has something to do with the way I am defining my client? hopefully someone has some tips or ideas on this
export const storeData = async (data) =>{
const uri = `mongodb+srv://plantmaster:${password}#cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`;
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1
});
const newPLantData = { name: "Company Inc", address: "Highway 37" };
await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{
if(err) throw err;
console.log(result)
})
await client.close();
};
I am calling this function on an express post route like so
// store data
app.post('/store', async function (req, res) {
await storeData(req.body);
res.send('data was stored')
})
i was facing the same error, but i fixed it by waiting 1500ms before closing the connection.
setTimeout(() => {client.close()}, 1500)
Try this example approach
import { MongoClient } from "mongodb";
const handler = async (req, res) => {
if (req.method === "POST") {
const { email } = req.body;
if (!email || !email.includes("#")) {
res.status(422).json({ message: "Entered email is not valid" });
return;
}
const url = <your-mongo-url>
const client = new MongoClient(url);
await client.connect();
const collection = client.db("events").collection("newsletter");
try {
await collection.insertOne({ email });
return res.status(201).json({
message: "You have successfully signed up to newsletters!",
email,
});
} catch (error) {
throw res.status(500).json({ message: "Server error occured" });
} finally {
client.close();
}
}
};
export default handler;
I have a problem with .get request.
Somehow it is not returning anything? (GET http://localhost:8080/admin net::ERR_EMPTY_RESPONSE)
Any suggestions?
Get Route,With this I'm trying to filter all items by their username:
app.get("/:username", verify, (req, res) => {
console.log("Welcome to roffys server");
Todo.find({ username: req.params.username }).then((err, todo) => {
if (err) {
console.log("Error retrieving todos");
} else {
res.json(todo);
}
});
});
Verify function,here I'm verifying my auth-token,I console logged it and it is working fine:
const jwt = require("jsonwebtoken");
module.exports = function (req, res, next) {
const token = req.header("auth-token");
console.log("-----token", token);
if (!token) return res.status(401).send("Access Denied");
try {
const verified = jwt.verify(token, "secretkey");
req.user = verified;
} catch (err) {
res.status(400).send("Invalid token");
next();
}
};
FE Side with ReactJS :
componentDidMount() {
const { getAll, setPageCount } = this.props.actions;
axios
.get(`http://localhost:8080/${localStorage.getItem("username")}`, {
headers: {
"auth-token": localStorage.getItem("auth-token"),
},
})
.then((res) => {
getAll(res.data);
setPageCount();
console.log("--------res.data", res.data);
})
.catch((err) => {
console.log("err", err);
});
}
app.get("/:username", verify, (req, res, next) => {
console.log("Welcome to roffys server");
Todo.find({ username: req.params.username }).then((err, todo) => {
if (err) {
console.log("Error retrieving todos");
return next(err);
} else {
res.json(todo);
}
});
});
try to add next to your handler and call it when you receive an error.
I want to insert a large array object in a Mongoose collection with the help of node worker thread, but it is not responding. I tried it without node worker thread and it's working fine, but with worker thread it's not working.
This is my worker file worker.js:
const { isMainThread, parentPort } = require("worker_threads");
const User = require("./models/user");
const csv = require("csvtojson");
if (!isMainThread) {
console.log("In Worker Thread");
parentPort.on("message", (csvFilePath) => {
csv()
.fromFile(csvFilePath)
.then((jsonObj) => {
User.insertMany(jsonObj)
.then((res) => {
console.log(res);
parentPort.postMessage("result");
})
.catch((err) => {
parentPort.postMessage("error");
console.log(err);
});
});
});
}
This is my main tread file. From here I am sending the data CSV file path. With that path, I will read the CSV file and convert it to the array of JSON. I want to insert this array into a MongoDB collection with the help of Mongoose.
// main thread file
const app = require("express")();
const formidable = require("formidable");
const mongoose = require("mongoose");
const User = require("./models/user");
const csv = require("csvtojson");
mongoose.connect("mongodb://localhost:27017/fileUpload", {
useNewUrlParser: "true",
useUnifiedTopology: true,
});
mongoose.connection.on("error", (err) => {
console.log("err", err);
});
mongoose.connection.on("connected", (err, res) => {
console.log("mongoose is connected");
});
const { isMainThread, Worker } = require("worker_threads");
let worker;
if (isMainThread) {
console.log("In main thread");
worker = new Worker("./worker.js");
worker.on("message", (data) => {
// console.log("Got Message=>", data);
});
worker.on("error", (data) => {});
worker.on("exit", (data) => {});
}
app.get("/", (req, res) => {
worker.postMessage("from main thread");
res.status(200).json("Hellow World");
});
app.post("/upload", (req, res, next) => {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
const csvFilePath = files.file.path;
csv()
.fromFile(csvFilePath)
.then((jsonObj) => {
console.log(jsonObj);
worker.postMessage(csvFilePath);
worker.on("message", (data) => {
res.json({ fields, files, data });
});
});
});
});
app.listen(5001, () => {
console.log("Server Is Running");
});
I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;