Trying to create signin and signup using express and MongoDB. In postman the data is perfectly passed but couldn't save the data into mongoDB cluster.
IN this file connection to the db is created and also confused whether i am connected to the db or not in this file, I created schema for the user details to be provided
//Index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db = process.env.DATABASE;
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db")
);
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
//User.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new Schema({
name: {
type: String,
max: 32,
required: true,
min: 6,
},
email: {
type: String,
required: true,
max: 32,
},
password: {
type: String,
max: 1022,
min: 8,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("User", userSchema);
//Auth.js
const router = require("express").Router();
const User = require("../model/User");
router.post("/register", (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const name = {
name: req.body.name,
email: req.body.email,
};
res.send(user);
user.save();
});
module.exports = route[![enter image description here][1]][1]r;
Step 1
First, you should create a server after your MongoDB is connected. So, put your server logic inside mongoose.connect connect. This will assure that when yo u try to create a new user, MongoDB is already connected.
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db");
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
);
Step 2
Use create method to create new user document:
router.post("/register", async (req, res) => {
const user = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
return res.status(200).json(user);
});
Related
When I'm uploading data about my new user I don't get any information back with the new json file where is saved my user, I only get '{}' and that's all. I'm sending here my code and what I get in Postman.
index.js
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const mongoose = require('mongoose');
const { CLIENT_RENEG_LIMIT } = require('tls');
const { application } = require('express');
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('Connected to Mongoose server'))
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use('/api/users', userRoute);
app.use('/api/auth', authRoute);
app.listen(process.env.PORT || 5200, ()=>{
console.log('Listening on port 5200');
});
auth.js
const router = require('express').Router();
const user = require('../models/user');
//REJESTRACJA
router.post('/rejestracja', async (req, res)=>{
const newUser = new user({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const saveduser = newUser.save();
res.status(201).json(saveduser);
}catch(err){
res.status(500).json(err);
}
});
module.exports = router
user.js
const mongoose = require('mongoose');
const {Boolean} = require('webidl-conversions');
const UserSchema = new mongoose.Schema({
username: { type: 'string', unique: true, required: true},
email: { type: 'string', unique: true, required: true},
password: { type: 'string', required: true, unique: true},
admin: { type: 'Boolean', default: false},},
{timestamps: true}
)
module.exports = mongoose.model('User', UserSchema);
postman screenshot
i m creating a small shop app with:
node.js & express and mongoose
and I m facing a problem when I try to send the data to the mongoose database
this is my product class
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: { type: String, required: true },
price: { type: Number, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, required: true }
});
module.exports = mongoose.model("Product", productSchema);
and this is the function to send in the controller
exports.postAddProduct = (req, res, next) => {
console.log(req.user);
const product = new Product({
title: req.body.title,
price: req.body.price,
description: req.body.description,
imageUrl: req.body.imageUrl,
userId: req.user });
product
.save()
.then((result) => {
console.log("Product created!");
res.redirect("/admin/products");
})
.catch((err) => {
console.log(err);
});
};
and this is the error
Error: Product validation failed: userId: Path `userId` is required.
at ValidationError.inspect (C:\Users\lenovo\Desktop\CURRENT_PROJECTS\node_tuto\node_modules\mongoose\lib\error\validation.js:48:26)
at formatValue (internal/util/inspect.js:745:19)
at inspect (internal/util/inspect.js:319:10)
also when I print the req.user in the function exports.postAddProduct it gives me undefined
this is app.JS
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs");
app.set("views", "./views");
const path = require("path");
const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const pageNotFoundController = require("./controllers/404");
const mongoose = require("mongoose");
const User = require("./models/user");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use((req, res, next) => {
User.findById("62c71d0ab0312958a8082d6f")
.then((user) => {
console.log('user' + user)
req.user = user;
// next();
})
.catch((err) => console.log(err));
next();
});
app.use("/admin", adminRoutes.routes);
app.use(shopRoutes);
app.use(pageNotFoundController.getPageNotFound);
mongoose
.connect(
"HERE MY URL "
)
.then((result) => {
User.findOne().then((user) => {
if (!user) {
const user = new User({
name: 'Aimen',
email: 'Aimen#',
cart: {
items: []
}
});
user.save();
} else {
console.log('user already there');
}
});
console.log("Connected to MongoDB");
app.listen(3000);
})
.catch((err) => console.log(err));
Is your req.user a string on an object?
If is a string you can try something like: mongoose.Types.ObjectId(string).
exports.postAddProduct = (req, res, next) => {
console.log(req.user);
const product = new Product({
title: req.body.title,
price: req.body.price,
description: req.body.description,
imageUrl: req.body.imageUrl,
userId: mongoose.Types.ObjectId(req.user)
});
product
.save()
.then((result) => {
console.log("Product created!");
res.redirect("/admin/products");
})
.catch((err) => {
console.log(err);
});
};
the bug was because in the middleware i was commenting the next() fun so the programme was stopping there
I keep getting this error message whenever i try to populate my "product" page from MongoDB.
I have added the body-parser dependency.
N.B
I stored the product images in my Public folder and i am storing the imagePath in MongoDB.
Here's a snippet of my code
From my App.js
const express = require('express');
const ejs = require('ejs');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const Product = require('./models/products');
From my product Model...
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
path: {
type: String,
required: true
},
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
},
{timestamps : true});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
Also from my App.js files
app.get('/product/create', (req, res) => {
res.render('upload', { title: 'Add Products'});
});
app.post('/', (req, res) => {
console.log(req.body);
})
//Looping through all products
app.get('/product', (req, res) => {
Product.find().sort({ createdAt: -1})
.then((result) => {
res.render('product', { title: 'All Products', products : result})
})
.catch((err) => {
console.log(err);
})
});
//POST request to product route
app.post('/product', (req, res) => {
const product = new Product(req.body);
product.save()
.then((result) => {
res.redirect('/product');
})
.catch(err => console.log(err));
});
I am developing an API using NodeJS with the functionality of user registration and login. When a user register, I get
"Error: WHERE parameter "email" has invalid "undefined" value" this
error."
I have checked similar question and answer here and tried every one of them, but none has worked for me.
app.js file
```
//use path module
const path = require('path');
//use express module
const express = require('express');
//use ejs view engine
const ejs = require('ejs');
//use bodyParser middleware
const bodyParser = require('body-parser');
//use mysql database
const mysql = require('mysql');
const app = express();
//Setting port number
const port = process.env.PORT || 619;
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user:'root',
password: '',
database: 'home_automation_db'
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.locals.stuff = {
url : req.originalUrl
}
next();
});
//connecting to database
mysqlConnection.connect((err) =>{
if(!err)
console.log('DB connection successful');
else
console.log('connection failed \n Error: '+JSON.stringify(err, undefined, 2));
});
var Users = require('./controllers/lightController');
app.use('/users', Users);
//server listening
app.listen(port, () => {
console.log('Server is running at port '+port);
});
lightcontroller.js
```var bodyParser= require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var generator = require('generate-password');
var nodemailer = require('nodemailer');
const bcrypt = require('bcrypt');
const cors= require('cors')
const jwt = require('jsonwebtoken');
const express =require('express')
const users = express.Router();
const User = require('../models/User');
users.use(cors());
process.env.SECRET_KEY = 'secret';
```
```
// Login controller
users.post('/register', function (req, res) {
const userData = {
user_name: req.body.username,
email: req.body.email,
password: req.body.password,
location: req.body.location,
house_number: req.body.house_number
}
User.findOne({
where: {
email: req.body.email
}
}).then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData).then(user => {
res.json({ status: user.email + "registered" })
}).catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({ error: "user already exist." })
}
}).catch(err => {
res.send('error: '+err)
})
});
```
User model
const Sequelize = require('sequelize')
const db = require("../database/db")
module.exports = db.sequelize.define(
'user_tb',
{
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
user_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
house_number: {
type: Sequelize.STRING
}
},
{
timestamps: false,
freezeTableName: true
}
)
As #messerbill said the most probable cause is the sending of data as undefined
Try adding config after post data to your post request on the client side so it sets proper content-type:
axios.post('http://localhost:9000/api/login', {
email: this.state.email,
password: this.state.password,
}, {
'content-type': 'x-www-form-urlencoded'
}).then(res => {
console.log(res);
if(res.status) {
console.log('User is logged in');
}
}).catch(err => console.log(err))
I'm trying to build server side back-end code for my website.
I tried app.get request in postman and it worked but when I tried
app.post request in postman it didn't work and gave me errors.
I tried all the solution that was available online and I could understand (I'm Ubuntu user).
Error Screenshot that I get in Postman
The following image will show you the error and format I used in postman
Server.js File (main server file)
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const app = express();
const mongoose = require("mongoose");
require("dotenv").config();
mongoose.Promise = global.Promise;
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// // DB config
mongoose.set("useCreateIndex", true);
// const db = require("./config/keys").mongoURI;
// Connect to MongoDB
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
// Models
const { User } = require("./models/user");
//====================================================
// USERS
//====================================================
app.post("/api/users/register", (req, res) => {
const user = new User(req.body);
user.save((err, doc) => {
if (err) return res.json({ success: false, err });
res.status(200).json({ success: true, userdata: doc });
});
});
app.get("/", (req, res) => res.send("hello world"));
const port = process.env.PORT || 3002;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
User Model file (models/user.js)
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
email: {
type: String,
requrired: true,
trim: true,
unique: 1
},
password: {
type: String,
requrired: true,
minlength: 5
},
name: {
type: String,
requrired: true,
maxlength: 100
},
lastname: {
type: String,
requrired: true,
maxlength: 100
},
cart: {
type: Array,
default: []
},
history: {
type: Array,
default: []
},
role: {
type: Number,
default: 0
},
token: {
type: String
}
});
const User = mongoose.model("User", userSchema);
module.exports = { User };
pass this has a raw data from postman and then call the post api
{
"email": "rohan#getMaxListeners.com",
"password":"pass#123",
"name":"sher",
"lastname":"lock"
}
Postman request should be like below.
{
"email": "rohit***#gmail.com",
"password": "password#123",
"name": "sher",
"lastname": "lock"
}
You are sending an invalid JSON.
Use this JSON for sending Request.
{
"email":"rohan3131313#gmail.com",
"password":"password#123",
"name":"sher",
"lastname:"lock"
}