Data is not going in Database in MERN ---
Everything is looking fine and also got status 200 and alert "post created" but data is not going in my database.
How to debug this error. I have tried all solutions. At least tell me the possible reasons for this error. it will help me a lot.
Schema
const mongoose = require("mongoose");
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
picture: {
type: String,
required: false,
},
username: {
type: String,
required: true,
},
category: {
type: String,
required: false,
},
createDate: {
type: Date,
default: Date.now,
},
})
const post = new mongoose.model('post', postSchema);
module.exports = post;
server router
const express = require("express");
const router = express.Router();
const post = require("../schema/post-schema");
router.post('/create', async(req,res) => {
try{
console.log(req.body);
const { title, description, picture, username, category, createDate } = req.body;
const blogData = new post({
title:title,
description:description,
picture:picture,
username:username,
category:category,
createDate:createDate
});
console.log("user " + blogData);
const blogCreated = await blogData.save();
if(blogCreated)
{
return res.status(200).json({
message: "blog created successfully"
})
}
console.log("post "+post);
} catch(error){
res.status(500).json('Blog not saved '+ error)
}
})
module.exports = router;
client file
const initialValues = {
title: '',
description: '',
picture: 'jnj',
username: 'Tylor',
category: 'All',
createDate: new Date()
}
const CreateView = () => {
const [post, setPost] = useState(initialValues);
const history = useHistory();
const handleChange = (e) => {
setPost({...post, [e.target.name]:e.target.value});
}
const savePost = async() => {
try {
const {title, description, picture, username, category, createDate} = post;
console.log(post);
const res = await fetch('/create', {
method: "POST",
headers: {
"Content-Type":"application/json"
},
body: JSON.stringify({title, description, picture, username, category, createDate})
})
console.log(post);
console.log("res is "+ res);
if(res.status===200 )
{
window.alert("post created");
console.log(res);
}
}
catch(e){
console.log(`save post error ${e}`);
}
}
const classes = useStyles();
const url = "https://images.unsplash.com/photo-1543128639-4cb7e6eeef1b?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bGFwdG9wJTIwc2V0dXB8ZW58MHx8MHx8&ixlib=rb-1.2.1&w=1000&q=80";
return (
<>
<Box className={classes.container}>
<form method="POST">
<img src={url} alt="banner" className={classes.image}/>
<FormControl className={classes.form}>
<AddIcon fontSize="large" color="action" />
<InputBase placeholder="Title" className={classes.textfield} name="title" onChange={(e)=>handleChange(e)}/>
<Button variant="contained" color="primary" onClick={()=>savePost()}>Publish</Button>
</FormControl>
<TextareaAutosize aria-label="empty textarea" placeholder="Write here..." className={classes.textarea} name="description" onChange={(e)=>handleChange(e)}/>
</form>
</Box>
</>
)
}
export default CreateView;
I think problem is you checking status 200 , so your server returning status 200 in anyway as response . You have to check your server side , and check if is returning code 400 or anything else on failure .
Related
Just a simple React Native fetch request to MongoDB database. I'm trying to display dynamic JSON properties for a user's post, for example postedBy, title, etc. But when I set something like title or description I get nothing at all, just blankness.
Post.js
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
postdesc: {
type: String,
required: true
},
img: {
type: String,
required: true
},
postedBy: {
type: ObjectId,
ref: "User"
}
})
mongoose.model("Post", postSchema)
fetch api code
router.get('/allposts', requireLogin, (req, res)=>{
Post.find()
.populate('postedBy', '_id username')
.then( posts =>{
res.json({ posts })
})
.catch( err=>{
console.log(err)
})
})
fetch code
const [ data, setData ] = useState([])
useEffect(()=>{
AsyncStorage.getItem('user')
.then(async (data) => {
fetch('http://10.0.2.2:3000/allposts', {
headers: {
'Authorization': 'Bearer ' + JSON.parse(data).token
}
}).then(res=>res.json())
.then( result=>{
console.log(result)
setData(result.posts)
})
})
}, [])
return code
return(
<View style={styles.container}>
<View style={styles.c1}>
{
data.map(( item )=>{
return(
<View key={item}>
<Text style={styles.postedBy} >{ data.postedBy }</Text>
<Text style={styles.title} >{ data.title }</Text>
</View>
)
})
}
</View>
</View>
)
}
What I want is: The title of my post is "Here is a title from db".
What I'm getting is: The title of my post is [Blank space] .
Note: the console.log(result) is showing the post's json in console just fine.
LOG {"posts": [{"__v": 0, "title": "Here is a title"`...etc, etc }]}
how can i convert this working mongoose code to a working MYSQL code?, i have a project where i fetch data from online api that updates every 24hours auto, and i need to insert that data information to database mysql but im new to mysql. im using react and node for my project.
import fetch from 'node-fetch';
import mongoose, { mongo } from 'mongoose';
mongoose.connect("mongodb://127.0.0.1:27017/highscore");
const postSchema = new mongoose.Schema({
position: {
type: Number,
required: true
},
id: {
type: Number,
required: true
},
score: {
type: Number,
required: true
},
});
const Post = mongoose.model('Players', postSchema);
async function getPosts() {
const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
const response = await getPlayers.json();
for( let i = 0;i < response.players.length; i++){
const post = new Post({
position: response.players[i]['position'],
id: response.players[i]['id'],
score: response.players[i]['score'],
});
post.save();
}
}
getPosts();
SOME backend code i put together but have no idea where to add the api
app.post('/create', (req, res) => {
const position = req.body.position
const name = req.body.name
const alliance = req.body.alliance
const points = req.body.points
db.query("INSERT INTO stats (position, name, alliance, points) VALUES (?,?,?,?)",
[position, name, alliance, points],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send("Values Inserted")
}
}
);
});
*** COMPLETE CODE THAT FETCHES DATA FROM API ***
const Table = () => {
const [playerName, setPlayerName] = useState([]);
const [playerRank, setPlayerRank] = useState([]);
const [player, setPlayer] = useState([]);
const [perPage, setPerPage] = useState(10);
const [size, setSize] = useState(perPage);
const [current, setCurrent] = useState(1);
const [players, setPlayers] = useState();
const fetchData = () => {
const playerAPI = 'http://localhost:3008/api/players';
const playerRank = 'http://localhost:3008/api/highscore/players';
const getINFOPlayer = axios.get(playerAPI)
const getPlayerRank = axios.get(playerRank)
axios.all([getINFOPlayer, getPlayerRank]).then(
axios.spread((...allData) => {
const allDataPlayer = allData[0].data.players
const getINFOPlayerRank = allData[1].data.players
const newPlayer = allDataPlayer.map(name => {
const pr = getINFOPlayerRank.find(rank => name.id === rank.id)
return {
id: name.id,
name: name.name,
status: name.status,
alliance: name.alliance,
position: pr?.position,
score: pr?.score
}
})
setPlayerName(allDataPlayer)
setPlayerRank(getINFOPlayerRank)
console.log(getINFOPlayerRank)
console.log(newPlayer)
setPlayer(newPlayer)
})
)
}
useEffect(() => {
fetchData()
}, [])
I have done the first part correctly (upload the images to their folders), but I can't
upload the images to the DB
form.html
the form to upload the images while the user sign up for a new account
<div>
<label for="image">Upload Image</label>
<input type="file" id="image1" name="image1" value="" >
</div><div>
<label for="image">Upload Image</label>
<input type="file" id="image2" name="image2" value="" >
</div>
multer.js
to save the images in the folders
const path = require('path');
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname === 'image1') {
cb(null, './logic/uploads');
}
else if (file.fieldname === 'image2') {
cb(null, './logic/uploadp');
}
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
console.log('New image saved!')
}
});
module.exports = multer({ storage: storage });
route
const express = require('express');
const router = express.Router();
const multer = require('../logic/multer')
const { userSignup, userLogin } = require('../logic/Membership_Application');
router.post('/Register',
multer.fields([
{ name: 'image1', maxCount: 1 },
{ name: 'image2', maxCount: 1 },
]),
userSignup
);
router.post('/login', userLogin);
module.exports = router;
logic (data insertion)
const UsersSchema = await new jcs({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
password: hashedPassword,
nationality: req.body.nationality,
//here is the error(it was working with multer.singel but not with multer,fields)
img: {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
contentType: 'image/png'
},
img2: {
data: fs.readFileSync(path.join(__dirname + '/uploadp/' + req.file.filename)),
contentType: 'image/png'
}
}).save();
model(Database schema)
const db = require('mongoose');
//Database Creation
const UsersSchema = new db.Schema
({
name: { type: String },
email: { type: String },
phone: { type: String },
password: { type: String },
nationality: { type: String },
img:
{
data: Buffer,
contentType: String,
},
img2:
{
data: Buffer,
contentType: String,
},
})
var Users = db.model("Users", UsersSchema);
module.exports = Users;
app.js
const express = require('express');
const app = express();
require('dotenv/config');
const MembershipApplicationRouter = require('./route/Membership_Application');
const AdminRouter = require('./route/admin')
var bodyParser = require('body-parser');
const cors = require('cors');
const db = require('mongoose');
db.connect('mongodb-link',
{
useNewUrlParser: true,
useUnifiedTopology: true
});
const connection = db.connection;
connection.on('connected', () => { console.log("conected with cloud") });
connection.on('error', () => { console.log("error with database") });
app.use('/admin', AdminRouter);
app.use([
bodyParser.urlencoded({ extended: true }),
express.json(),
express.urlencoded({ extended: true })]);
app.use(cors());
app.use('/membershipApplication', MembershipApplicationRouter);
var port = process.env.PORT || 8080;
app.listen(port, () => {
console.log("Server Up and running");
})
module.exports = app;
I have this error msg
New image saved!
New image saved!
C:\Users\abs2\Desktop\m_a_test\logic\Membership_Application.js:79
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
^
TypeError: Cannot read properties of undefined (reading 'filename')
at userSignup (C:\Users\abs2\Desktop\m_a_test\logic\Membership_Application.js:79:84)
[nodemon] app crashed - waiting for file changes before starting...
The best practice is to store the file’s location in your server to mongoDB.
So that whenever you to access the file you fetch it’s location then return it back!!
I'm trying to create a very simple Content Management System for creating and updating blog posts. I managed to successfully create and delete blog posts but I'm having difficulty wrapping my head around when I try to edit them.
The problem I'm running into is if I have 3 fields that are Editable for the Blog Post.
1) Blog Topic
2) Blog Picture
3) Blog Content
If I edit 1 field such as Blog Topic with test data and I submit the changes, the data that was in Blog Picture and Blog Content get lost and submit nothing even though there was data there previously and I'm not sure why. However, if I set the defaultValue to my state whenever I save to make changes, the problem gets fixed but I want my inputs to have the initial value in there field also.
Here is my code:
import React from "react";
import ReactDOM from "react-dom";
import Header from "../common/Header";
import Footer from "../common/Footer";
import Adminediting from "../common/isEditing";
import Addblogtopic from "./Addblogtopic";
import { Modal, Button } from "react-bootstrap";
import { Link, Redirect } from "react-router-dom";
import Moment from "moment";
import dataTip from "data-tip";
import { confirmAlert } from "react-confirm-alert";
import CKEditor from "ckeditor4-react";
import blogtopicsService from "../../services/Blogservice";
import appController from "../../controllers/appController";
class Blogtopics extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
blogData: [],
blogCategory: "",
blogContent: "",
blogId: "",
hoverSelected: false,
isEditing: false,
fileObject: "",
fileName: "",
fileSize: "",
fileType: "",
filePayload: "",
blogPicture: "",
email: "",
firstName: "",
lastName: "",
roleId: "",
userId: "",
errorMsg2: false,
errorMsg3: false
};
}
Selectblogtopics = async () => {
const blogTopics = await blogtopicsService.selectblogTopics();
this.setState({
blogData: blogTopics
});
};
toggleHover = hoverState => {
this.setState({ hoverSelected: hoverState });
};
updateImage = e => {
let file = e.target.files[0];
var dataTypeURL = new FileReader();
var arrayBuffer = new FileReader();
this.setState({
fileObject: file,
fileName: file.name,
fileSize: file.size,
fileType: file.type
});
dataTypeURL.onload = e => {
this.setState({
filePayload: e.target.result,
blogPicture: e.target.result
});
};
dataTypeURL.readAsDataURL(file);
arrayBuffer.readAsArrayBuffer(file);
};
editBlog = editingState => {
this.setState({
isEditing: !editingState
});
//Publish Changes
setTimeout(async () => {
this.setState({
isLoading: false
});
const uploadData = {
blogCategory: this.state.blogCategory,
blogContent: this.state.blogContent,
modifiedDate: Moment().format("YYYY-MM-DD hh:mm:ss"),
blogId: this.state.blogId,
fileType: this.state.fileType,
fileName: this.state.fileName,
fileSize: this.state.fileSize,
filePayload: this.state.filePayload
};
const updateBlog = await blogtopicsService.editBlog(uploadData);
location.href = "/blog";
}, 1000);
}
};
handleClose = () => {
this.setState({ show: false });
};
handleShow = () => {
this.setState({ show: true });
};
onChange = async (e, blogId) => {
await this.setState({
[e.target.name]: e.target.value,
blogId: blogId
});
};
deleteBlog = blogId => {
confirmAlert({
customUI: ({ onClose }) => {
return (
<div className="custom-ui">
<h1>Are you sure</h1>
<p>You want to delete this blog?</p>
<button onClick={onClose}>Cancel</button>
<button
onClick={() => {
this.confirmDelete(blogId);
onClose();
}}
>
Confirm
</button>
</div>
);
}
});
};
confirmDelete = async blogId => {
// Delete the blog
const deleteBlog = await blogtopicsService.deleteBlog({ blog_id: blogId });
// Re-render the blog posts after deleting
await this.Selectblogtopics();
};
async componentDidMount() {
await this.userData();
await this.Selectblogtopics();
}
render() {
return (
<div className="fluid-container">
<div className="blogContainer">
<Header />
<Adminediting
title={this.props.match.path}
editState={this.editBlog}
/>
<div className="container">
<div className="editSection">
<div className="text-right">
<span className="data-tip-bottom" data-tip="Add Blog Post">
<i className="fas fa-plus" onClick={this.handleShow} />
</span>
</div>
</div>
<div className="blogContent">
{this.state.blogData.map((rows, index) => (
<div className="blogWrapper" key={index}>
{rows.blog_status === 1 ? (
<div
className="row"
>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<Modal.Title>Add Blog Post</Modal.Title>
</Modal.Header>
<Modal.Body>
<Addblogtopic
handleClose={this.handleClose}
selectblogTopics={this.Selectblogtopics}
/>
</Modal.Body>
</Modal>
<div className="col-md-4">
<img
src={
"https://s3-us-east-1.amazonaws.com/" +
rows.blog_thumbnail
}
alt="test"
/>
{this.state.isEditing === true ? (
<div className="input-group">
<input
type="file"
className="d-block mt-4"
name="blogPicture"
onChange={e => this.updateImage(e)}
/>
</div>
) : null}
</div>
<div className="col-md-6">
{this.state.isEditing === true ? (
<input
type="text"
name="blogCategory"
onChange={e => this.onChange(e, rows.blog_id)}
defaultValue={rows.blog_category}
/>
) : (
<Link
to={
"/blog/" +
rows.blog_id +
"/" +
appController.friendlyUrl(rows.blog_category)
}
id="blogUrl"
>
<h3
id="blogTopic"
dangerouslySetInnerHTML={{
__html: rows.blog_category
}}
/>
</Link>
)}
{this.state.roleId === 1 ? (
<div className="editSection">
<div className="text-right">
<span
className="data-tip-bottom"
data-tip="Delete Blog Post"
>
<i
className="far fa-trash-alt"
onClick={e => this.deleteBlog(rows.blog_id)}
/>
</span>
</div>
</div>
) : null}
<div
className={
this.state.hoverSelected == index
? "blogSection hover"
: "blogSection"
}
>
{this.state.isEditing === true ? (
<CKEditor
data={rows.blog_content}
onChange={(event, editor) => {
const data = event.editor.getData();
this.setState({
blogContent: data
});
}}
/>
) : rows.blog_content.length > 50 ? (
<div
className="cmsStyles"
dangerouslySetInnerHTML={{
__html: rows.blog_content.substr(0, 50) + " ..."
}}
/>
) : (
<div
className="cmsStyles"
dangerouslySetInnerHTML={{
__html: rows.blog_content
}}
/>
)}
</div>
</div>
</div>
) : null}
</div>
))}
</div>
</div>
</div>
<Footer />
</div>
);
}
}
export default Blogtopics;
Back End Data
var db = require("../dbconnection");
const AWS = require("aws-sdk");
var blog = {
insertblogPost: function(data, callback) {
var uniquePicture = "blogphoto" + "-" + data.fileName;
var awsFolder = "awsfolder" + "/" + uniquePicture;
db.query(
"insert blog_topics set blog_category=?, blog_thumbnail=?, blog_content=?, blog_author=?",
[data.blogTopic, uniquePicture, data.blogContent, "random user"]
);
var buf = new Buffer(
data.filePayload.replace(/^data:image\/\w+;base64,/, ""),
"base64"
);
//Upload file into AWS S3 Bucket
var s3 = new AWS.S3();
var params = {
Bucket: "testbucket",
Key: awsFolder,
Body: buf,
ContentType: data.fileType,
ACL: "public-read"
};
s3.putObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
return data;
}
}),
callback(true);
},
deleteBlog: function(data, callback) {
db.query(
"UPDATE blog_topics set blog_status=? where blog_id=?",
["0", data.blog_id],
callback
);
},
editBlog: function(data, callback) {
var uniquePicture = "blogphoto" + "-" + data.fileName;
var awsFolder = "awsfolder" + "/" + uniquePicture;
db.query(
"UPDATE blog_topics set blog_category=?, blog_thumbnail=?, blog_content=?, blog_author=?, modified_date=? where blog_id=?",
[
data.blogCategory,
uniquePicture,
data.blogContent,
"Test Username",
data.modifiedDate,
data.blogId
]
);
var buf = new Buffer(
data.filePayload.replace(/^data:image\/\w+;base64,/, ""),
"base64"
);
//Upload file into AWS S3 Bucket
var s3 = new AWS.S3();
var params = {
Bucket: "awsbucket",
Key: awsFolder,
Body: buf,
ContentType: data.fileType,
ACL: "public-read"
};
s3.putObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
return data;
//console.log(data);
}
}),
callback(true);
},
selectblogTopics: function(data, callback) {
db.query(
"select blog_id, blog_category, blog_thumbnail, blog_content, blog_status, blog_author, created_date, modified_date from blog_topics",
callback
);
},
selectblogArticle: function(data, callback) {
db.query(
"select blog_id, blog_category, blog_thumbnail, blog_content, blog_author, created_date from blog_topics where blog_id=?",
[data.blogId],
callback
);
},
editArticle: function(data, callback) {
var uniquePicture = "blogphoto" + "-" + data.fileName;
var awsFolder = "awsfolder" + "/" + uniquePicture;
db.query(
"UPDATE blog_topics set blog_category=?, blog_thumbnail=?, blog_content=?, blog_author=?, modified_date=? where blog_id=?",
[
data.blogCategory,
uniquePicture,
data.blogContent,
"test user",
data.modifiedDate,
data.blogId
]
);
var buf = new Buffer(
data.filePayload.replace(/^data:image\/\w+;base64,/, ""),
"base64"
);
//Upload file into AWS S3 Bucket
var s3 = new AWS.S3();
var params = {
Bucket: "awsfolder",
Key: awsFolder,
Body: buf,
ContentType: data.fileType,
ACL: "public-read"
};
s3.putObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
return data;
}
}),
callback(true);
}
};
module.exports = blog;
You can create a generic method to update all blog info.
setBlogProperty(index, propName, propValue) {
this.setState(state => {
state.blogData[index][propName] = propValue;
return state;
});
};
Then call this method on onChange event of your input element.
<input
type="text"
name="blogCategory"
onChange={e => this.setBlogProperty(index, 'blog_category', e.target.value)}
defaultValue={rows.blog_category}
/>
I'm trying to pass an object from a model to my route so I can finish my login system but I'm not recieving anything.
Model code:
const AWS = require('aws-sdk');
const bcrypt = require('bcryptjs');
const config = require('../config/config.json');
var dynamoose = require('dynamoose');
const express = require('express');
var Schema = dynamoose.Schema;
const USER_SCHEMA = new Schema({
username: {
type: String,
required: true
},
firstName: {
type: String
},
lastName: {
type: String
},
email: {
type: String,
required: true
},
credential: {
type: String
},
password: {
type: String,
required: true
}
})
const USER = module.exports = dynamoose.model('Usuarios', USER_SCHEMA);
module.exports.getUserByUsername = function (user, callback) {
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "Users",
KeyConditionExpression: "#us = :uuuu",
ExpressionAttributeNames: {
"#us": "username"
},
ExpressionAttributeValues: {
":uuuu": user
}
};
docClient.query(params, function (err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
data.Items.forEach(function (user, callback) {
console.log(user.username + ": " + user.password + user.email + user.firstName);
});
}
callback(null, user);
});
}
This is working fine, I can print user.username, user.password and so on, but for some reason my router is not importing the JSON
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
USER.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({
success: false,
"msg": "User not found"
});
}
USER.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign({
username: user
}, secret.secret, {
expiresIn: 86400
});
res.json({
success: true,
token: 'JWT ' + token,
user: {
user: user.username,
password: USER.password,
email: user.email
}
});
} else {
return res.json({
success: false,
msg: 'Wrong password'
})
}
});
});
});
The res.json from comparePassword should be the object from the route (which is the user model) but is not recieving a thing. I have tried with USER.username/email/etc user.username/email/etc but nothing works.
I know I must be missing something somewhere, but where?
Edit: Also tried with module.export.user = user; inside the model