I am creating MERN stack app and trying to save data in database.After data added successfully in database I am sending success message from node server and I want to show this message on front-end side but it is showing nothing though I am sending message from server.
Below is my code:
React code form.js
import React,{Component} from 'react';
import Axios from 'axios';
import swal from 'sweetalert';
class Form extends Component{
constructor(props){
super(props)
this.state = {
title:'',
detail:''
}
}
onTitleChange = (e) => {
this.setState({
title:e.target.value
});
}
onDetailChange = (e) => {
this.setState({
detail:e.target.value
});
}
handleSubmit = (e) => {
e.preventDefault();
Axios.post('http://localhost:5000/save',{
title:this.state.title,
detail:this.state.detail
}).then((msg) =>{
swal(msg);
}).catch((err) => {
console.log("React Error:",err);
});
}
render(){
return(
<div className="container">
<h2 id="formTitle">Add blog</h2>
<form>
<div>
<input type="text" className="validate" name="title" value={this.state.title} placeholder="Title" onChange={this.onTitleChange} required/>
</div>
<div>
<textarea type="text" value={this.state.detail} className="validate materialize-textarea" name="detail" placeholder="Detail" onChange={this.onDetailChange} required></textarea>
</div>
SUBMIT
</form>
</div>
)
}
};
export default Form;
saveData.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const blogs = require('../models/blogPost');
const mongoose = require('mongoose');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: true}));
const dburl = 'mongodb+srv://exp#cluster1-5ws.mongodb.net/expdb?retryWrites=true'
router.post('/save',(req,res) => {
const data = {
title: req.body.title,
detail: req.body.detail
}
const newBlog = new blogs(data);
mongoose.connect(dburl, {useNewUrlParser: true,useUnifiedTopology:true}).then((resp) =>{
newBlog.save().then(() => {
res.json({msg:"Data inserted"});
}).catch((err) => {
console.log("Insertion error", err);
});
}).catch((err) => {
console.log("database error: ",err);
});
});
module.exports = router;
mongoose database schema blogPost.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogPostSchema = new Schema({
title:String,
detail:String,
date:{
type:String,
dafault:Date.now()
}
});
const BlogPost = mongoose.model('BlogPost',BlogPostSchema);
module.exports = BlogPost;
Someone please let me know what I m doing wrong any help would be appreciated.
Thanks
In Axios then block Simply add res.data to get response from server.
Axios.post('http://localhost:5000/save',{
title:this.state.title,
detail:this.state.detail
}).then((res) =>{
swal(res.data);
}).catch((err) => {
console.log("React Error:",err);
});
THANKS
Related
I am trying to post a data to the mongoose database but I keep getting Axios error 404. I need help. Is there something wrong in my code?
This is my modal, it contains the front end of the website
AddForm.jsx
import React, { useState } from "react";
import axios, { Axios } from "axios";
const AddForm = () =>{
const [appData, setAppData] = useState({
pName:"",
appNum:"",
datetime:"",
})
const submit =(e) =>{
e.preventDefault();
axios.post("/addAppDetails", {
pName: appData.pName,
appNum: appData.appNum,
datetime: appData.datetime,
})
.then(res =>{
console.log(res.appData)
})
.catch((error)=>{
console.log(error);
});
}
const handle = (e) => {
const newData={...appData}
newData[e.target.id] = e.target.value
setAppData(newData)
console.log(newData)
}
return(
<Form onSubmit={(e) => submit(e)}>
<Form.Group>
<Form.Control
id="pName"
type="text"
placeholder="Patient Name"
onChange={(e) => handle(e)}
value={appData.pName}
required/>
</Form.Group>
<Form.Group>
<Form.Control
id="appNum"
type="text"
placeholder="Appointment Number"
onChange={(e) => handle(e)}
required/>
</Form.Group>
<Form.Group>
<Form.Control
id="datetime"
as="textarea"
placeholder="Date and Time"
onChange={(e) => handle(e)}
required/>
</Form.Group>
<Button variant="success" type="submit" block>Update Appointment</Button>
</Form>
)
}
export default AddForm;
This is my backend, it contains the route/api for functionality
server.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
app.use(express.json()); //prints body request
app.use(cors());
const JWT_SECRET = "sdaikdhjiIHDiu8987J(#?!dDSF8645DAsadA[]ds54aASD()21asd1SFP";
const mongooseURL =
"mongodb+srv://client:lolpassword#cluster0.lfrgaha.mongodb.net/?retryWrites=true&w=majority";
//server
app.listen(5001, () => {
console.log("Server started successfully.");
});
//connect with DB
mongoose
.connect(mongooseURL, {
useNewUrlParser: true,
})
.then(() => {
console.log("Connected to database successfully");
})
.catch((e) => console.log(e));
require("./models/appointmentDetails");
const AppDetails = mongoose.model("AppointmentDetails");
//add data to db
app.post("/addAppDetails", async(req, res) => {
const newAppDetails = new AppDetails(req.body);
try{
newAppDetails.save();
res.send(newAppDetails);
}
catch(err){
console.log(err);
res.status(500).send(error);
}
});
This is my database model.
appointmentDetails.js
const AppDetails = new mongoose.Schema(
{
pName: String,
appNum: String,
datetime: String,
status: String,
action: String,
},
{
collection: "AppointmentDetails",
}
);
mongoose.model("AppointmentDetails", AppDetails);
404 means the url (including http://host:port) that you are using to send request & expecting response from, doesn't exist in your case.
While sending request, check if your node server is receiving the response or not, using logs, or a global middleware function logging every request info. This way you'll see whether the server is receiving the request or not, and thus find the problem.
As suggested in the answer by #thillon (now deleted probably), most likely in your case the url is incomplete (doesn't contain the server's host:port part), so you can follow their way to ensure that your request url is proper and thus make sure that your server is able to receive request is this particular case.
Global middleware function
Write this right after your app.use(express.json()) statement.
app.use((req, res, next) => {
console.log(req.body)
// or log anything helpful in the req object
next();
})
I have setup a webpage to search a number via user input and if it's available in the SQL Server database, 2 text boxes would show up with the data using AXIOS GET endpoint. Then I'm trying to get those ID's of the data rows and if the user needs to UPDATE it, then UPDATE it via AXIOS PUT endpoint. The issue is once user clicks the UPDATE button it throws an error PUT http://localhost:5000/api/customerOrder/[object%20Object],[object%20Object] 404 (Not Found)
Here's what I've tried
Server endpoints :
dboperations.js
var config = require('./dbconfig');
const sql = require('mssql');
async function getallcustomerOrders(){
try{
let pool = await sql.connect(config);
let orders = await pool.request()
.query("SELECT * FROM [100].[dbo].[OELINCMT_SQL] order by ID desc");
return orders.recordsets;
}
catch (error){
console.log(error);
}
}
async function getcustomerOrders(orderNumber){
try{
let pool = await sql.connect(config);
let orders = await pool.request()
.input('input_parameter', sql.NChar, orderNumber)
.query("SELECT ID,cmt FROM [100].[dbo].[OELINCMT_SQL] where LTRIM(ord_no) = LTRIM(#input_parameter)");
return orders.recordsets;
}
catch (error){
console.log(error);
}
}
async function updateComments(ID){
try {
let pool = await sql.connect(config);
let orders = await pool.request()
.input('ID', sql.NChar, ID)
.query(`SELECT ID,cmt FROM [100].[dbo].[OELINCMT_SQL] WHERE ID = #ID`);
let order = orders.recordset.length ? orders.recordset[0] : null;
if (order) {
await pool.request()
.input('cmt', req.body.cmt)
.query(`UPDATE [100].[dbo].[OELINCMT_SQL] SET cmt = #cmt WHERE ID = #ID;`);
order = { ...order, ...req.body };
res.json(order);
} else {
res.status(404).json({
message: 'Record not found'
});
}
} catch (error) {
res.status(500).json(error);
}
}
module.exports = {
getallcustomerOrders : getallcustomerOrders,
getcustomerOrders : getcustomerOrders,
updateComments : updateComments
}
api.js
var Db = require('./dboperations');
var dboperations = require('./dboperations');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
const { request, response } = require('express');
var app = express();
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', router);
router.use((request,response,next)=> {
console.log('middleware');
next();
})
router.route('/customerOrder').get((request,response)=>{
dboperations.getallcustomerOrders().then(result => {
response.json(result[0]);
console.log(result[0]);
})
})
router.route('/customerOrder/:orderNumber').get((request,response)=>{
dboperations.getcustomerOrders(request.params.orderNumber).then(result => {
response.json(result[0]);
console.log(result[0]);
})
})
router.route('customerOrder/:ID').put((request,response)=>{
dboperations.updateComments(request.params.ID).then(result => {
response.json(result[0]);
console.log(result[0]);
})
})
var port = process.env.PORT || 5000;
app.listen(port);
console.log('Customer Order API is running at ' + port);
dboperations.getcustomerOrders().then(result => {
console.log(result);
})
dboperations.getallcustomerOrders().then(result => {
console.log(result);
})
dboperations.updateComments().then(result => {
console.log(result);
})
Client :
EmailFaxDetails.js : This is the page user enters the number
import React, { useState,useEffect } from 'react'
import FetchOrderDetails from './FetchOrderDetails';
import axios from 'axios'
import '../App.css';
const EmailFaxDetails = () => {
const [orderNumber, setOrderNumber] = useState('');
const [id, setId] = useState([]);
const [isShown, setIsShown] = useState(false);
const url = `http://localhost:5000/api/customerOrder/${orderNumber}`
useEffect(() => {
axios.get(url)
.then(response => {
console.log(response.data)
setId(response.data)
})
.catch((err) => console.log(err));
}, [url]);
const handleChange = event => {
setOrderNumber(event.target.value);
console.log(event.target.value);
};
const handleClick = event => {
event.preventDefault();
setIsShown(true);
console.log(orderNumber);
}
return(
<div>
<br></br>
<br></br>
Order Number: <input placeholder="Order Number" type="text" id="message" name="message" onChange={handleChange} value={orderNumber} autoComplete="off" />
{id.map((idnum) => (
<div key={idnum.ID}>
<br></br>
ID : {idnum.ID}
</div>
))}
<button onClick={handleClick}>Search</button>
{isShown && <FetchOrderDetails ord_no={orderNumber} ID={id}/>}
</div>
)
}
export default EmailFaxDetails;
FetchOrderDetails.js : In this page user get's the output if the number is available in SQL server and let then UPDATE accordingly.
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../App.css';
const FetchOrderDetails = ({ord_no,ID}) => {
const [data, setData] = useState([]);
const url = `http://localhost:5000/api/customerOrder/${ord_no}`
useEffect(() => {
axios.get(url)
.then(response => {
console.log(response.data)
setData(response.data)
})
.catch((err) => console.log(err));
}, [url]);
const url2 = `http://localhost:5000/api/customerOrder/${ID}`
const onSubmit = () => {
axios.put(url2)
.then((response) => {
if (response.status === 200) {
alert("Comment successfully updated");
ID.history.push(`/customerOrder/${ord_no}`);
} else Promise.reject();
})
.catch((err) => alert("Something went wrong"));
}
if(data) {
return(
<div>
{data.map((order) => (
<div key={order.ID}>
<br></br>
ID : {order.ID}
<br></br>
Email/Fax: <input defaultValue={order.cmt} placeholder="Sales Ack Email" id="salesAck" style={{width: "370px"}} />
</div>
))}
<div>
<br></br>
<br></br>
<button onClick={onSubmit}>Update</button>
</div>
</div>
)
}
return (
<h1>Something went wrong, please contact IT!</h1>
)
}
export default FetchOrderDetails;
What I suspect is the issue might be coming from the EmailFaxDetails.js page while trying to pass the ID since there are 2 ID's per number the user search. I might be wrong, if anyone could find the error and help making it correct I would really appreciate it.
I think problem here
setId(response.data)
You need retrieve only id and same for for orderid
I am confused as to how to communicate from the nodejs server to the reactjs login component on whether login was successful or not.
I have a reactjs component that handles login as follows:
Login.js
import React, {useState} from 'react';
import axios from "axios";
const Login = () => {
const [user,setUser] = useState({email:"",password:""});
const handleSubmit = (e) => {
e.preventDefault();
console.log(user);
axios.post('http://localhost:5000/login',user)
.then(function (response) {
console.log(response);
console.log("Successfully done");
})
.catch(function (error) {
console.log("error here")
console.log(error.message);
});
}
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div>Email:</div>
<div><input type="text" name="email" placeholder='Enter your email'
onChange={(e)=>setUser({...user,email:e.target.value})}
/></div>
<div>Password:</div>
<div><input type="password" name="password" placeholder='Enter your password'
onChange={(e)=>setUser({...user,password:e.target.value})}
/></div>
<div><input type="submit" value="Add" /></div>
</form>
</div>
)
}
export default Login;
and an expressjs backed that processes the login
server.js
const express = require("express");
const mongoose = require("mongoose");
const User = require("./Models/Conn.js");
const bcrypt = require("bcryptjs");
//const Route1 = require("./Routes/Route.js");
const cors = require('cors');
const app = express();
//app.use("/api",Route1);
app.use(express.json({extended:true}));
app.use(express.urlencoded({extended:true}));
app.use(cors());
const url = "mongodb+srv://pekele:pekele#cluster0.yqaef.mongodb.net/myDatabase?retryWrites=true&w=majority";
mongoose.connect(url)
.then(()=>console.log("connected to database successfully"))
.catch(err=>console.log(err));
app.get("/",(req,res)=> {
res.send("<h1>Welcome Guest</h1>");
});
app.get("/signup",(req,res)=> {
res.json({"id":"1"});
})
app.post("/signup",(req,res)=> {
const {email,password} = req.body;
bcrypt.genSalt(10)
.then(salt=> {
bcrypt.hash(password,salt)
.then(hash => {
const user = new User({email,password:hash});
user.save()
.then(()=>console.log("Successfully saved"))
.catch(error=>console.log(error));
})
}).catch(err=>console.log(err));
})
app.post("/login",(req,res)=> {
const {email,password} = req.body;
console.log(`My email is ${email}`)
User.findOne({email:email}, function (err, doc) {
console.log(doc);
if(doc == null) {
//How do i let react login page know that there is no user with such email
}
if(doc != null) {
const emailDB = doc.email;
const passwordDB = doc.password;
bcrypt.compare(password,passwordDB)
.then(res => {
//How do I tell the react login page that the login was successful
}).catch(err=>console.log(err));
}
});
})
app.listen(5000,()=> console.log("Server listening on port 5000"));
The problem is how do I communicate to the react login page whether the login was successful or not in the app.post("/login",(req,res) ... Thanks
You can send data via -
res.json(data)
res.send("Submitted Successfully!")
res.status(200).send(message)
I’ve spent most of a day looking into this and trying to make it work. This is an app with a React/Redux front end, and a Node/Express/Mongoose/MongoDB back end.
I currently have a Topics system where an authorized user can follow/unfollow topics, and an admin can Add/Remove topics.
I want to be able to upload an image file when submitting a new topic, and I want to use Cloudinary to store the image and then save the images path to the DB with the topic name.
The problem I am having is that I am unable to receive the uploaded file on the back end from the front end. I end up receiving an empty object, despite tons of research and trial/error. I haven’t finished setting up Cloudinary file upload, but I need to receive the file on the back end before even worrying about that.
SERVER SIDE
index.js:
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const app = express();
const router = require("./router");
const mongoose = require("mongoose");
const cors = require("cors");
const fileUpload = require("express-fileupload");
const config = require("./config");
const multer = require("multer");
const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");
app.use(fileUpload());
//file storage setup
cloudinary.config({
cloud_name: "niksauce",
api_key: config.cloudinaryAPIKey,
api_secret: config.cloudinaryAPISecret
});
const storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: "images",
allowedFormats: ["jpg", "png"],
transformation: [{ width: 500, height: 500, crop: "limit" }] //optional, from a demo
});
const parser = multer({ storage: storage });
//DB setup
mongoose.Promise = global.Promise;
mongoose.connect(
`mongodb://path/to/mlab`,
{ useNewUrlParser: true }
);
mongoose.connection
.once("open", () => console.log("Connected to MongoLab instance."))
.on("error", error => console.log("Error connecting to MongoLab:", error));
//App setup
app.use(morgan("combined"));
app.use(bodyParser.json({ type: "*/*" }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
router(app, parser);
//Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log("server listening on port: ", port);
TopicController/CreateTopic
exports.createTopic = function(req, res, next) {
console.log("REQUEST: ", req.body); //{ name: 'Topic with Image', image: {} }
console.log("IMAGE FILE MAYBE? ", req.file); //undefined
console.log("IMAGE FILES MAYBE? ", req.files); //undefined
const topic = new Topic(req.body);
if (req.file) {
topic.image.url = req.file.url;
topic.image.id = req.file.publid_id;
} else {
console.log("NO FILE UPLOADED");
}
topic.save().then(result => {
res.status(201).send(topic);
});
};
router.js
module.exports = function(app, parser) {
//User
app.post("/signin", requireSignin, Authentication.signin);
app.post("/signup", Authentication.signup);
//Topic
app.get("/topics", Topic.fetchTopics);
app.post("/topics/newTopic", parser.single("image"), Topic.createTopic);
app.post("/topics/removeTopic", Topic.removeTopic);
app.post("/topics/followTopic", Topic.followTopic);
app.post("/topics/unfollowTopic", Topic.unfollowTopic);
};
CLIENT SIDE
Topics.js:
import React, { Component } from "react";
import { connect } from "react-redux";
import { Loader, Grid, Button, Icon, Form } from "semantic-ui-react";
import {
fetchTopics,
followTopic,
unfollowTopic,
createTopic,
removeTopic
} from "../actions";
import requireAuth from "./hoc/requireAuth";
import Background1 from "../assets/images/summer.jpg";
import Background2 from "../assets/images/winter.jpg";
const compare = (arr1, arr2) => {
let inBoth = [];
arr1.forEach(e1 =>
arr2.forEach(e2 => {
if (e1 === e2) {
inBoth.push(e1);
}
})
);
return inBoth;
};
class Topics extends Component {
constructor(props) {
super(props);
this.props.fetchTopics();
this.state = {
newTopic: "",
selectedFile: null,
error: ""
};
}
onFollowClick = topicId => {
const { id } = this.props.user;
this.props.followTopic(id, topicId);
};
onUnfollowClick = topicId => {
const { id } = this.props.user;
this.props.unfollowTopic(id, topicId);
};
handleSelectedFile = e => {
console.log(e.target.files[0]);
this.setState({
selectedFile: e.target.files[0]
});
};
createTopicSubmit = e => {
e.preventDefault();
const { newTopic, selectedFile } = this.state;
this.props.createTopic(newTopic.trim(), selectedFile);
this.setState({
newTopic: "",
selectedFile: null
});
};
removeTopicSubmit = topicId => {
this.props.removeTopic(topicId);
};
renderTopics = () => {
const { topics, user } = this.props;
const followedTopics =
topics &&
user &&
compare(topics.map(topic => topic._id), user.followedTopics);
console.log(topics);
return topics.map((topic, i) => {
return (
<Grid.Column className="topic-container" key={topic._id}>
<div
className="topic-image"
style={{
background:
i % 2 === 0 ? `url(${Background1})` : `url(${Background2})`,
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
backgroundSize: "cover"
}}
/>
<p className="topic-name">{topic.name}</p>
<div className="topic-follow-btn">
{followedTopics.includes(topic._id) ? (
<Button
icon
color="olive"
onClick={() => this.onUnfollowClick(topic._id)}
>
Unfollow
<Icon color="red" name="heart" />
</Button>
) : (
<Button
icon
color="teal"
onClick={() => this.onFollowClick(topic._id)}
>
Follow
<Icon color="red" name="heart outline" />
</Button>
)}
{/* Should put a warning safety catch on initial click, as to not accidentally delete an important topic */}
{user.isAdmin ? (
<Button
icon
color="red"
onClick={() => this.removeTopicSubmit(topic._id)}
>
<Icon color="black" name="trash" />
</Button>
) : null}
</div>
</Grid.Column>
);
});
};
render() {
const { loading, user } = this.props;
if (loading) {
return (
<Loader active inline="centered">
Loading
</Loader>
);
}
return (
<div>
<h1>Topics</h1>
{user && user.isAdmin ? (
<div>
<h3>Create a New Topic</h3>
<Form
onSubmit={this.createTopicSubmit}
encType="multipart/form-data"
>
<Form.Field>
<input
value={this.state.newTopic}
onChange={e => this.setState({ newTopic: e.target.value })}
placeholder="Create New Topic"
/>
</Form.Field>
<Form.Field>
<label>Upload an Image</label>
<input
type="file"
name="image"
onChange={this.handleSelectedFile}
/>
</Form.Field>
<Button type="submit">Create Topic</Button>
</Form>
</div>
) : null}
<Grid centered>{this.renderTopics()}</Grid>
</div>
);
}
}
const mapStateToProps = state => {
const { loading, topics } = state.topics;
const { user } = state.auth;
return { loading, topics, user };
};
export default requireAuth(
connect(
mapStateToProps,
{ fetchTopics, followTopic, unfollowTopic, createTopic, removeTopic }
)(Topics)
);
TopicActions/createTopic:
export const createTopic = (topicName, imageFile) => {
console.log("IMAGE IN ACTIONS: ", imageFile); //this is still here
// const data = new FormData();
// data.append("image", imageFile);
// data.append("name", topicName);
const data = {
image: imageFile,
name: topicName
};
console.log("DATA TO SEND: ", data); //still shows image file
return dispatch => {
// const config = { headers: { "Content-Type": "multipart/form-data" } };
// ^ this fixes nothing, only makes the problem worse
axios.post(CREATE_NEW_TOPIC, data).then(res => {
dispatch({
type: CREATE_TOPIC,
payload: res.data
});
});
};
};
When I send it like this, I receive the following on the back end:
(these are server console.logs)
REQUEST: { image: {}, name: 'NEW TOPIC' }
IMAGE FILE MAYBE? undefined
IMAGE FILES MAYBE? undefined
NO FILE UPLOADED
If I go the new FormData() route, FormData is an empty object, and I get this server error:
POST http://localhost:3090/topics/newTopic net::ERR_EMPTY_RESPONSE
export const createTopic = (topicName, imageFile) => {
console.log("IMAGE IN ACTIONS: ", imageFile);
const data = new FormData();
data.append("image", imageFile);
data.append("name", topicName);
// const data = {
// image: imageFile,
// name: topicName
// };
console.log("DATA TO SEND: ", data); // shows FormData {} (empty object, nothing in it)
return dispatch => {
// const config = { headers: { "Content-Type": "multipart/form-data" } };
// ^ this fixes nothing, only makes the problem worse
axios.post(CREATE_NEW_TOPIC, data).then(res => {
dispatch({
type: CREATE_TOPIC,
payload: res.data
});
});
};
};
Solution was to switch to using Firebase instead, and deal with image upload on the React client (this was attempted with cloudinary but with no success). The resulting download url can be saved to the database with the topic name (which is all I wanted from cloudinary) and now it is displaying the correct images along with the topics.
I have created a chat app using nodejs/express, mongodb, reactjs. When I type in the chat box and on clicking send button the data get's stored inside mongodb but how can I display it on client side. In code below I am not able to display it on client side. In server.js I am not able to emit the messages. What I am doing wrong in server.js ? The data is not reaching frontend from backend/database.
Code:
server.js:
const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const message = require('./model/message')
const app = express();
const mongoURI = require('./config/keys').mongoURI;
mongoose.connect(mongoURI, {useNewUrlParser: true})
.then()
.catch( err => console.log(err));
let db = mongoose.connection;
const port = 5000;
let server = app.listen(5000, function(){
console.log('server is running on port 5000')
});
let io = socket(server);
io.on("connection", function(socket){
console.log("Socket Connection Established with ID :"+ socket.id)
socket.on('disconnect', function(){
console.log('User Disconnected');
});
let chat = db.collection('chat');
socket.on('SEND_MESSAGE', function(data){
let message = data.message;
let date = data.date;
// Check for name and message
if(message !== '' || date !== ''){
// Insert message
chat.insert({message: message, date:date}, function(){
socket.emit('output', [data]);
});
}
});
//Code below this is not working:
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('RECEIVE_MESSAGE', res);
});
})
chat.js:
import React, { Component } from 'react'
import './chat.css'
import io from "socket.io-client";
export default class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
date: '',
messages: []
};
const socket = io('localhost:5000');
this.sendMessage = event => {
event.preventDefault();
if(this.state.message !== ''){
socket.emit('SEND_MESSAGE', {
message: this.state.message,
date: Date.now()
});
this.setState({ message: '', date: '' });
}
};
socket.emit('RECEIVE_MESSAGE', data => {
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({
messages: [...this.state.messages, data],
});
console.log(this.state.message);
console.log(this.state.messages);
};
}
render() {
return (
<div>
<div id="status"></div>
<div id="chat">
<div className="card">
<div id="messages" className="card-block">
{this.state.messages.map((message, index) => {
return (
<div key={index} className="msgBox"><p className="msgText">{message.message}</p></div>
)
})}
</div>
</div>
<div className="row">
<div className="column">
<input id="inputmsg" type="text" placeholder="Enter Message...."
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
</div>
<div className="column2">
<button id="send" className="button" onClick={this.sendMessage}>Send</button>
</div>
</div>
</div>
</div>
)
}
}
Screenshot of mongo shell:
Mongoose documentation specifies the correct usage of .find() method . You can find it here.
To cut the chase you need to give the method an object model that you are looking for. So for example if you were looking for objects with specific date field you could use:
chat.find({ "date": <some-date> }, function(err, objects) { ... });
If you want to fetch all object from the collection you can use:
chat.find({}, function(err, objects) { ... });