I have a simple get method which returns all users from my mongodb.
Also i've connected redis.
And now i need to use redis caching mechanism to make it faster.
How can i set and get data from cache using redis and just in case there is nothing in cache, get data from mongodb ?
app.js
const usersRoute = require("./routes/users");
const redis = require("redis");
const client = redis.createClient();
app.use("/users", usersRoute);
client.on("connect", () => console.log("Redis client connected!"));
client.on("error", err => {
console.log(`Error ${err}`);
});
User.js
const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
name: {
type: String,
require: true
}
});
module.exports = mongoose.model("User", UserSchema);
users.js
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.get("/", async (req, res) => {
const users = await User.find();
res.send(users);
});
Related
I'm trying to add data in the form of users to my MongoDB database which is in my local drive, but no data is being added according to post requests on postman. I have written an API to handle this post request on userRoute file. Below is the file.
const User = require("../models/userModel");
const express =require("express");
const router = express.Router();
//Fetching all users from the database
router.route("/").get((req,res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json(`There was an error: ${err.message}`));
});
//Adding user to the database
router.route("/add").post((req,res) =>{
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json("User added successfully!!"))
.catch(err => res.status(400).json(`There was an error:${err.message}`))
});
module.exports = router;
Below is also my User schema in the userModel file
const mongoose = require ("mongoose");
const Schema = mongoose.Schema
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 5,
maxlength: 15
}
},
{
timestamps: true
}
)
const User = mongoose.model("User",userSchema);
module.exports = User;
My server file containing the connection to the database and routing
//require the installed packages
const express = require("express");
const cors = require("cors");
const mongoose = require ("mongoose");
const res = require("express/lib/response");
const App = express();
require("dotenv").config();
//middlewares
App.use(cors());
App.use(express.json());
//setting environment variables and explicitly declared variables
const port = process.env.PORT || 3000;
const db = process.env.MONGODB_URI || "mongodb://localhost/tizi";
//routes
const exerciseRoute = require("./routes/exerciseRoute");
const userRoute = require("./routes/userRoute");
//App to use required routes(Use App.set and not App.use)
App.set("/Users",userRoute);
App.set("/Exercises",exerciseRoute);
//setting up server
App.listen(port,() =>{
console.log(`Server is running on port : ${port}`)
});
//connecting to database
mongoose.connect(db,
{
useNewUrlParser:true,
useUnifiedTopology : true
},
(err) => {
err
? console.log(`there is a problem: ${err.message}`)
: console.log("connected to database successfully");
});
//maintaining connection to database
mongoose.connection;
Try to use
await User.create({username});
Instead of save()
This code is of the connect to the mongodb i can see in console that successfully connect to mongodb i cant create a new user by sending data in the request boby.
const mongoose = require('mongoose');
const mongoURI = "mongodb://localhost27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"
const connectToMongo = () => {
mongoose.connect(mongoURI, () => {
console.log("Connected to Mongo Successfully");
})
}
module.exports = connectToMongo;
This code is for authentication end point
const express =require('express');
const User = require('../models/User');
const router = express.Router();
const user = require('../models/User');
router.post('/', (req,res)=>{
res.send(req.body);
const user = User(req.body);
console.log(req.body);
user.save;
})
module.exports = router;
Its just problem with the connection string and a typo.
I have a mongodb collection with a few examples and I was trying to display them on my get method but it keeps showcasing the Processing, Please wait... buffer screen without outputting any result. I am wondering why it takes so long and does not display even after an hour and more when it displayed quite quickly on my simpler tests before.
This is my Usermodel
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema(
{
username: { type:String,unique:true,required:true},
email:{type:String,unique:true,required: true},
password:{type: String,required:true,},
isAdmin:{type:Boolean,default: false,}, },
{
timestamps: true,
});
const userModel = mongoose.model("users_list",userSchema);
This is the user router
const express = require('express');
const userModel = require('../models/users');
const { model } = require('mongoose');
const router = require("express").Router();
router.get("/getUser",(req,res)=> {
userModel.find({},(err,result)=>{
if(err){
res.json("There is an error");
}
else{
res.json(result);
console.log("got result");
console.log(result);
}
});
res.send("Ok");
});
module.exports = router;
And here is how my index.js where all the routers are called and fixated.
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const userRouter = require('./apis/routers/userRouter');
const cors = require("cors");
dotenv.config();
mongoose
.connect(process.env.MONG_URL)
.then(() => console.log("DB Connection Successful!"))
.catch((err) => {
console.log(err);
});
app.use(cors);
app.use(express.json());
app.use('/api/users',userRouter);
I have given the right MongoDB URL and it is not enclosed in quotation marks or anything from .env
And right here as you can see in the image, the postman keeps doing this
This sending request is unending and doesn't fetch the data at all. How can I resolve this?
Code never executes to the console.log("in") so findOne is not being run. RoboT3 also doesnt show auth db. Mongo version is the latest 4.0.3.
controllers/authentication.js
const User = require('../models/user');
exports.signup = (req, res, next) => {
console.log(req.body)
const email = req.body.email;
const password = req.body.password;
// check for duplicate users by email
User.findOne({email: email}, (err, existingUser) => {
console.log("in")
if (err) {return next(err)}
// if duplicate found, return error
if (existingUser) {
return res.status(422).send({error: 'Email is in use'});
}
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {return next(err); }
res.json(user);
})
});
// if not, create and save record and return
}
index.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require ('morgan');
const router = require('./router');
const mongo = require('mongodb');
mongo.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
const App = express();
// App setup
App.use(morgan('combined'));
App.use(bodyParser.json());
router(App);
// Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(App);
server.listen(port);
console.log("server running on port " + port);
router.js
const authentication = require('./controllers/authentication');
module.exports = function (app) {
app.post('/signup', authentication.signup);
}
models/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema ({
email: {type: String, unique: true, lowercase: true},
password: String
});
const ModelClass = mongoose.model('user', userSchema);
module.exports = ModelClass;
Why not use mongoose in your index.js ?
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
let db = mongoose.connection;
db.once('open', function callback () {
console.log("connected to db");
});
I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.js, keys.js
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// BodyParser Middleware
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
//Connect to Mongo
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use('./api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started'));
Item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
items.js
const express = require('express');
const router = express.Router();
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items))
});
module.exports = router;
keys.js
module.exports = {
mongoURI: 'mongodb://tset:tset123#ds241012.mlab.com:41012/mern_shopping'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items
Change this
app.use('./api/items', items);
to
app.use('/api/items', items);
and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})