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
Related
I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.
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);
});
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))
After several hours. Research in StackOverflow. There are a lot of articles about this issue. But I can't figure out what I'm wrong here.
My code:
models/Team.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const teamSchema = new Schema({
name: { type: String, minLength: 1, required: true },
description: { type: String },
});
mongoose.model('teams', teamSchema);
models/Division.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const divisionSchema = new Schema({
name: { type: String, minLength: 1, required: true },
description: { type: String },
});
mongoose.model('teams', divisionSchema);
And I was required in index.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./config/keys');
require('./models/Team');
require('./models/Division');
mongoose.Promise = global.Promise;
mongoose.connect(keys.mongoURI, { useNewUrlParser: true });
const app = express();
app.use(bodyParser.json());
require('./routes/teamRoutes')(app);
const port = process.env.PORT || 5000;
app.listen(port);
routes/teamRoutes.js
const mongoose = require('mongoose');
const Team = mongoose.model('teams');
module.exports = (app) => {
app.get('/api/teams', async (req, res) => {
const teamsList = await Team.find({});
res.send(teamsList);
});
};
If I delete require('./models/Division');, It works. Why is that?
If not, I got the error:
throw new mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `teams` model once compiled.
mongoose.model('teams', divisionSchema);
'teams' should be 'division' in models/Division.js I guess
In expressJs project, I try to use sequelize to interact with database.
This is my model/user.js :
module.exports = (sequelize, DataTypes) => {
sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: true
},
password: DataTypes.STRING
})
}
And this is models/index.js :
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}
const sequelize = new Sequelize(
config.db.database,
config.db.user,
config.db.password,
config.db.options
)
fs
.readdirSync(__dirname)
.filter((file) =>
file !== 'index.js'
)
.forEach((file) => {
var a = path.join(__dirname, file);
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
The problem is in this line
const model = sequelize.import(path.join(__dirname, file));
Which returns undefine to model variable.
What did I miss here? I appreciate any hint?
Whole code on Github : here
Problem could be because of a missing return
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', { // Missing return
email: {
type: DataTypes.STRING,
unique: true
},
password: DataTypes.STRING
})
}
Change to
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING,
unique: true
},
password: DataTypes.STRING
});
return User;
}