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.
Related
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?
Context: I am using mongoDB to store my data on my first API, it's made in node.js. I'm currently working on creating a login system. When I post the account to my API I set the _id value to the email address so to access it I can just do api.com/logins/email. Whenever I do that I get this in return
{"_id":"email","password":"password","__v":0}
However when I switch the server location (from my server to my laptop for dev testing) I can no longer access the logins by _id. I can still access the entire collection, but when I attempt to call specifically by the _id I get Cannot GET /logins/email This also happens if after the fact I reopen the API server on my personal server
In order to fix this I have to delete all the collections in that area and re add one from the app. Once I do this everything works again however when my app goes live I would want to have this fixed because otherwise everyone would need to remake their accounts when I do work on the API
With this being my first API I'm kind of at a loss for what's happening and why it is, any help would be appreciated
Relevant code from sign in page (yes I am aware that base64 isn't encrypting I just haven't change it yet)
const login = async () =>{
encrypted = (await encrypt())
console.log(email.toUpperCase())
var mail = email.toUpperCase()
var test = await fetchSingleData(url,mail)
console.log(test)
if (test==null){
console.log("Invalid email")
return
}
console.log(test.password == encrypted)
if (encrypted == test.password){
console.log("I'm in")
setEmail("")
setPassword("")
navigation.navigate("Sheet")
}
else console.log("Invalid Password")
}
const encrypt = async () =>{
var enc = Base64.encode(password)
console.log(enc)
return enc
}
Mongoose connection code
const express = require('express')
const app = express()
const mongoose = require('mongoose')
require('dotenv/config')
const bodyParser = require('body-parser')
const MONGOBD_URL = process.env.DB_CONNECTION
var https = require("https")
var fs = require("fs");
var path = require("path")
app.use(bodyParser.json())
//Import routes
const postsRoute = require('./routes/posts')
const loginRoute = require("./routes/logins")
app.use('/posts', postsRoute)
app.use('/logins', loginRoute)
//ROUTES
app.get('/',(req,res)=>{
res.send("We are on home")
})
//LISTENER
app.listen(19010)
//Connect to DB
mongoose.connect(MONGOBD_URL,{useNewUrlParser:
true},()=>{console.log("connected to DB")})
module.exports = app;```
Routing
const express = require('express')
const router = express.Router();
const Login = require("../Models/Login")
//GET ALL ACCOUNTS
router.get('/',async (req,res)=>{
console.log("req")
try{
const logins = await Login.find()
res.json(logins)
}catch(err)
{
res.json({message: err})
}
})
// CREATES ACCOUNT
router.post('/', async (req,res) => {
const login = new Login({
_id: req.body._id,
password: req.body.password
})
//SPECIFIC ACCOUNT
router.get('/:postID', async (req,res) =>{
try{
const login = await Login.findById(req.params.postID)
res.json(login)
}
catch(err){res.json({message:err})}
})
const savedLogin = await login.save()
try{
res.json(savedLogin)
}catch(err){
res.json({message: err})
}
})
//DELETE ACCOUNT
router.delete('/:postID', async (req,res) => {
try{
const remove = await Post.remove({_id:req.params.postID})
res.json(remove)
}
catch(err){res.json({message:err})}
})
module.exports = router
Data example in database
okay so let us get to this...I'm not too sure what the cause of this issue is, but let us go through your code and try to isolate it. So we will begin by neatening things up a little.
starting with your login code:
const login = async () => {
encrypted = (await encrypt())
var mail = email.toUpperCase()
var test = await fetchSingleData(URL, mail)
// [TIP]: this is sufficient to achieve the same logic.
if (!test) {
return
}
if (encrypted == test.password) {
setEmail("")
setPassword("")
navigation.navigate("Sheet")
}
else
console.log("Invalid Password")
}
//...
const encrypt = async () => {
return Base64.encode(password)
}
Okay let check out your route configuration.
// [TIP]: import everything first
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
// [TIP]: const on everything that wont change
const https = require("https")
const fs = require("fs");
const path = require("path")
require('dotenv/config')
const MONGOBD_URL = process.env.DB_CONNECTION
const app = express()
app.use(bodyParser.json())
//Connect to DB
// [FIX]: Connect to the database first before referencing it in your routes
// [NOTE]: Express is a static server and cannot change after configuring
// the routes that you have.
mongoose.connect(MONGOBD_URL,
{ useNewUrlParser: true },
() => console.log("connected to DB"))
//Import routes
const postsRoute = require('./routes/posts')
const loginRoute = require("./routes/logins")
// I do not know what goes on here
app.use('/posts', postsRoute)
// or here, but suspect your issue lies here.
app.use('/logins', loginRoute)
//ROUTES
app.get('/', (req, res)=>{
res.send("We are on home")
});
//LISTENER
app.listen(19010, () => console.log('server listening on port 19010'));
module.exports = app;
Im still not sure what the problem could be with this code, my suspicion is still with your database connection.
So in the end the issue was my brackets. They were set up in a way that so that the singular get was only created when I did a POST
When trying to post user data to database with mongoose, so the problem is like this:
In order for user to get credits i'm charging him "money" with stripe library so when im trying to post data into database im getting this error- TypeError: req.user.save is not a function
Here's the code:
//User model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserSchema = new Schema({
googleId: String,
credits: { type: Number, default: 0}
});
mongoose.model('users', UserSchema);
//Route code
const keys = require('../config/keys');
const stripe = require('stripe')(keys.stripeSecretKey);
const User = require('../models/User');
module.exports = app => {
app.post('/api/stripe', async (req, res) => {
const charge = await stripe.charges.create({
amount: 500,
currency: 'usd',
description: '$5 for 5 credits',
source: req.body.id
});
req.user.credits += 5;
const user = await req.user.save();
res.send(user);
});
};
//Index file
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const bodyParser = require('body-parser');
const passport = require('passport');
require('./models/User');
require('./services/passport');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
require('./routes/authRoutes')(app);
require('./routes/billingRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
console.log('The server is running!');
.save() it's a method that should be used over the MongoDB object.
First you should find your user in your MongoDB, like for example:
(async()=>{
try{
const user = await User.findById(userID)
// now user is an Object which has the .save() method
// now you can modify the name of the userm for example
user.name = "new name"
// after saving the changes wit .save() method
await user.save() // you're connecting with DB to communicate about introducing new data
// ...
}catch(err){
// ...
}
})()
Hope is useful.
I have creating a REST API using Express, Mongoose, and MongoDB,
but it's saving only two property name and email and increase one more property then it's not saving.
below is my model and Router file.
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema;
const userModel = new UserSchema({
sirName: String,
name: String,
email: String
});
module.exports = mongoose.model('user',userModel);
const express = require('express');
const router = express.Router();
const user = require('../models/user');
router.get('/users', (req, res, next)=>{
res.json({
'message': 'Fetch All User from Database'
});
});
//post request
router.post('/user', (req, res)=> {
const userData = new user({
sirName: req.body.sirName,
name : req.body.name,
email: req.body.email
})
userData.save()
.then(item =>{
res.send(item)
})
})
module.exports= router;
Here is your schema
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema;
const userModel = new UserSchema({
sirName: String,
name: String,
email: String
});
module.exports = mongoose.model('user', userModel);
Your routes
const express = require('express');
const router = express.Router();
const user = require('../model/Users');
router.get('/users', (req, res, next)=>{
res.json({
'message': 'Fetch All User from Database'
});
});
//post request
router.post('/user', (req, res)=> {
const userData = new user({
sirName: req.body.sirName,
name : req.body.name,
email: req.body.email
})
userData.save()
.then(item =>{
res.send(item)
})
})
module.exports= router;
And here is your root file
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const app = express();
const db = require('./setup/keys').my_url
const userRoutes = require('./routes/UserRoutes');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
mongoose
.connect(db, {useNewUrlParser:true, useUnifiedTopology:true})
.then(() => console.log('Connected'))
.catch(err => console.log(err));
app.use('/hi', userRoutes);
app.listen(port, () => console.log(`Server is running at ${port}`))
After Sending JSON Data
All the data are saved in the databases
It works fine!!
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);
});