First time using Next.js, I'm trying to implement a Node.js server with MongoDB database, schema models and routes.
I'm not sure what I'm doing wrong, since I tried a lot of combinations, as you can see in the comments in my code. I need to use the models but I'm getting the following error:
"OverwriteModelError: Cannot overwrite termscon model once compiled."
server/models/TermsCon.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const TermsConSchema = new Schema({
_id: {
type: String,
required: true,
default: "1"
},
text: {
type: String,
required: true,
default: "Lorem Ipsum"
}
});
// const TermsCon = mongoose.model.termscon || mongoose.model('termscon', TermsConSchema);
// module.exports = TermsCon;
// module.exports = mongoose.model('termscon', TermsConSchema);
// export default mongoose.model.TermsCon || mongoose.model('termscon', TermsConSchema)
module.exports = TermsCon = mongoose.model('termscon', TermsConSchema);
server/routes/api/termscons.js:
const express = require('express')
const mongoose = require('mongoose');
const router = express.Router()
const TermsCon = require('../../models/TermsCon')
// const TermsCon = mongoose.model('termscon')
router.get('/', (req, res) => {
TermsCon.find()
.then(tc => {
res.json(tc)
})
});
module.exports = router;
server/index.js:
const express = require('express')
const next = require('next')
const mongoose = require('mongoose')
const port = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
mongoose
.connect(process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const server = express()
server.use("/api/termscons", require("./routes/api/termscons"))
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`Server started on port ${port}`)
})
})
pages/index.js:
import axios from 'axios'
import { useState, useEffect } from 'react'
export default function Home() {
const [ tc, setTc ] = useState()
useEffect(() => {
axios.get('/api/termscons')
.then(res => {
setTc(res.data)
})
.catch(err =>console.log("ERR: ", err))
}, [])
return (
<div>
{tc ?
<p>{tc}</p>
: null}
</div>
)
}
Is it something wrong with the way I'm exporting my schema? With the way I'm connecting to my MongoDB? The routes? Pages?
Any idea will be much appreciated! Thanks!
So I changed the structure:
I gave up creating a custom server since it didn't helped me at all in my Next.js app.
So I don't have any server/index.js anymore or server/routes/api. Actually, there is no "server" folder at all. I simply created a mongodb connection separatelly to help me connect to my database, wich I call at each server api call, like so:
utils/dbConnect.js:
import mongoose from 'mongoose'
async function dbConnect() {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
}
export default dbConnect
Since I don't have a custom server anymore, I don't have server/routes/api either. So for the api routes I use the default next.js api folder:
pages/api/termscons.js:
import dbConnect from '../../../utils/dbConnect'
import TermsCon from '../../../models/TermsCon'
export default async function handler(req, res) {
await dbConnect()
switch (req.method) {
case 'GET':
try {
const tc = await TermsCon.find()
res.status(200).json(tc)
} catch (error) {
res.status(400).json({ itemnotfound: "No item found" })
}
break
default:
res.status(400).json({ itemnotfound: "No item found" })
break
}
}
To conclude, I have a folder with all my models in my app main folder:
models/TermsCon.js:
import mongoose from 'mongoose'
const TermsConSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
default: "1"
},
text: {
type: String,
required: true,
default: "Lorem Ipsum"
}
});
export default mongoose.models.TermsCon || mongoose.model('termscon', TermsConSchema);
Related
First, I'll show my backend code to see how I'm pulling the information, then ill show the data, and the model of what I'm precisely pulling
export const getPosts = async (req, res, next) => {
try {
const post = await Post.find()
if(!post) return next(createError('No Posts Found'))
res.status(200).json(post)
} catch (error) {
next(error)
}
}
export const createPost = async (req, res, next) => {
const body = req.body
try {
const post = new Post({ ...body })
if(!post) return next(createError('Cannot create Post'))
await post.save()
return res.status(200).json(post)
} catch (error) {
next(error)
}
}
I'm not using the createPost function in the frontend of my code; I'm strictly keeping it in the backend. Now, here's my model schema of how the data is shaped.
import mongoose from "mongoose";
const PostSchema = new mongoose.Schema({
img: {type: String, required: true},
title: {type: String, required: true},
desc: {type: String, required: true},
date: {type: String, default: Date},
}, {
timestamps: true
})
export default mongoose.model("Post", PostSchema);
Now, onto the frontend. Im using axios to pull the information
const [events, setEvents] = useState([])
const [loading, setLoading] = useState(true)
const url = 'http://localhost:6000/api/events'
useEffect(() => {
const getEvents = async () => {
const { data: res } = await axios.get(url)
setEvents(res)
};
getEvents()
}, [])
Here's where I'm mapping and attempting to load the data on the screen.
{loading ? <h1>Loading Events...</h1> :
<div>
{events.map(event => (
<div>
<div>
<div key={event._id}>
<img src={event.img} alt="Jamil the founder" />
<div>
<p>{event.title}</p>
<p>{event.desc}</p>
</div>
</div>
</div>
</div>
))}
</div>}
When I console.log it here's what appears
Heres how I'm setting up my connection in the backend
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import postRoutes from './Routes/post.js'
import cors from 'cors'
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
dotenv.config()
const PORT = process.env.PORT || 8000;
mongoose.connect(process.env.DATABASE_ACCESS, {
useNewUrlParser: true,
useUnifiedTopology: true,
}, () => console.log('Database Connected'))
app.use((err, req, res, next) => {
const status = err.status || 500
const message = err.message || "something went wrong"
return res.status(status).json({
success: false,
status,
message
})
})
app.use(
cors({
methods: ["GET", "POST"],
credentials: true,
})
);
app.use('/api', postRoutes)
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
6000 port already reserved port change to 3000 and then try again.
You don't need to set an object as response to the data you get from axios, i think you just do a typo since data is one of the property from the response, how about trying like this :
const [events, setEvents] = useState([])
const [loading, setLoading] = useState(true)
const url = 'http://localhost:6000/api/events'
useEffect(() => {
const getEvents = async () => {
const res = await axios.get(url)
setEvents(res.data)
};
getEvents()
}, [])
update2: this will work since you re using ES6 so you can use top lvl await :
import "dotenv/config"; //do it like this and remove the extra line "dotenv.config()"
//......
// optional to listnening if you re connected
mongoose.connection.once("open", () => {
console.log("connection ready!");
})
try {
await mongoose.connect(process.env.DATABASE_ACCESS);
} catch (err) {
console.log(`Process failed... ${err}`);
}
const PORT = process.env.PORT || 8000; //or the port of your choice
app.listen(PORT, () => {
console.log(`app is running on port ${PORT}...`)
});
than change your URL on the frontend to match the port.
I am trying to build a rest API with node express and MongoDB, when I try to test my API with postman I getting this response
"message": "Cannot read property 'firstName' of undefined"
bellow I have attached all my server-side code. first, I have config my application with mongo and started developing the models and respective controllers for that model. inside the controller, I have defined my get and post methods. I don't understand why I am getting that response message when I try to send a post request.
Server Config
import Express from "express";
import Mongoose from "mongoose";
import CorsOptions from "cors";
import bodyParser from "body-parser";
import apiRoutes from "./routes/api.js";
const app = Express();
app.use("/api", apiRoutes);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const CONNECTION_URL =
"mongodb+srv://user:Index-123#cluster0.uhijm.mongodb.net/SustainableIQ?retryWrites=true&w=majority";
const PORT = process.env.PORT || 5000;
Mongoose.connect(CONNECTION_URL)
.then(() =>
app.listen(PORT, () => console.log("server running on port: ${PORT}"))
)
.catch((error) => console.log(error.message));
Routes
import Express from "express";
import {
getApi,
createUser,
adminCreate,
} from "../controller/UserController.js";
const router = Express.Router();
router.get("/", getApi);
router.post("/create", createUser);
router.post("/create-admin", adminCreate);
export default router;
Nodejs Controller
import postUser from "../models/postUser.js";
import adminSchema from "../models/adminUser.js";
export const getApi = async (req, res) => {
try {
postUser
.find()
.exec()
.then((result) => {
if (result) {
res.status(200).json(result);
}
});
} catch (error) {
res.status(404).json({ message: error.message });
}
};
export const adminCreate = async (req, res) => {
try {
const admin = req.body;
const newAdmin = new adminSchema(admin);
newAdmin.firstName = req.body.firstName;
newAdmin.secondName = req.body.secondName;
await newAdmin.save();
res.status(201).json(newAdmin);
} catch (err) {
res.status(409).json({ message: err.message });
}
};
export const createUser = async (req, res) => {
try {
const post = req.body;
const newPost = new postUser(post);
newPost.firstName = req.body.firstName;
newPost.secondName = req.body.secondName;
newPost.position = req.body.position;
newPost.compnayName = req.body.compnayName;
newPost.contactNumber = req.body.contactNumber;
newPost.email = req.body.email;
await newPost.save();
res.status(201).json(newPost);
} catch (err) {
res.status(409).json({ message: err.message });
}
};
mongodb schema
import Mongoose from "mongoose";
var adminSchema = Mongoose.Schema({
firstName: { type: String, required: true },
secondName: { type: String, required: true },
createdAt: {
type: Date,
default: Date.now,
},
});
var adminSchema = Mongoose.model("adminSchema", adminSchema);
export default adminSchema;
I am working on a MERN stack and I am trying to display a single user's data on its own page. The route works on the server-side in Postman, I am able to get the user by Id. But on the client-side I get a 400 bad request when trying to get the user information with axios from that route. could their be a problem with any of my endpoints?
Component
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import axios from 'axios'
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Navbar from '../layouts/navbar'
// import './userDashboard.css'
class userDashboard extends Component {
state = {
user: {}
}
getUser = () =>{
const userId = this.props.match.params.userId
axios.get('/api/users/' + userId ).then(res=>{
const user = res.data;
this.setState({
user
})
}).catch((err)=> console.log(err))
}
componentDidMount() {
this.getUser()
}
render() {
const { name } = this.state.user
return (
<div>
<Navbar />
<h1 className="title-text">Hello { name }</h1>
</div>
);
}
}
userDashboard.propTypes = {
// logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
});
export default connect(mapStateToProps)(userDashboard);
controller
router.get("/:userId", (req, res) => {
const { userId } = req.params;
if(!userId){
return res.status(400).json({message: "user id not found"})
}
if(!ObjectId.isValid(userId)){
return res.status(400).json({ message: "userId not valid"})
}
User.findById(userId,(err, user) => {
if(err) {
res.status(500);
console.log("errr 500")
} else {
if(!user)
res.status(400).json({message:"user not found"});
res.status(200).json({"user" : user})
}
})
})
server.js
const express = require("express");
const path = require('path');
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
const users = require("./controllers/api/users")
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(`${__dirname}/client/build`));
// app.get('/*', (req, res) => {
// res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*', (req, res) => {
// res.sendFile(path.join(__dirname, '/../', 'build', 'index.html'));
// });
//DATA BASE CONFIGURATION
const dbkeys = require("./config/key").mongoURI;
mongoose.connect(
dbkeys,
{useNewUrlParser: true} )
.then(()=> console.log("database connection successful"))
.catch(err => console.log(err))
app.use(passport.initialize());
require("./config/passport")(passport);
app.use("/api/users", users);
// app.use("/api", users)
const port = 5000;
app.listen( port, () => console.log("server us up and running on port 5000!"))
Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork:{type: [ClassworkSchema], default: []},
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
// const User = mongoose.model('users', UserSchema);
// const Classwork = mongoose.model('Classwork', ClassworkSchema );
// module.exports = {
// User : User ,
// // Classwork : Classwork
// }
module.exports = mongoose.model("users", UserSchema);
You need to include the server side localhost endpoint in your GET request from the client side.
getUser = () =>{
const userId = this.props.match.params.id;
axios.get(`http://localhost:5000/api/users/${userId}`).then(res=>{
const user = res.data;
this.setState({
user
})
}).catch((err)=> console.log(err))
}
You are requesting a response from the server side , so it is required to include the correct path to which the response should travel.
You will need to include this path in all of the requests you send from the client side to the server side. I recommend using a proxy in the client side package.json as below,
"proxy":"http://localhost:5000"
This will let you write your endpoint path as you have done in your GET request implementation.
For the CORS error,
Install CORS in your server side package.json as npm install cors
Then import CORS to your server.js as const cors = require('cors');
Then use CORS as middleware app.use(cors());
I trying to display data on the client-side of my react application. when sending a get request for single user by id on my server-side I get a 200 ok status and the user information. But when trying to make an axios call on the client-side i get 400 status error. I believe it is how I use req.params in the server-side get request. how can I refactor the GET request so that I can get the response on the client-side.
Controller
router.get("/:userId", (req, res) => {
const { userId } = req.params;
if(!userId){
return res.status(400).json({message: "user id not found"})
}
if(!ObjectId.isValid(userId)){
return res.status(400).json({ message: "userId not valid"})
}
User.findById(userId,(err, user) => {
if(err) {
res.status(500);
console.log("errr 500")
} else {
if(!user)
res.status(400).json({message:"user not found"});
res.status(200).json({"user" : user})
}
})
})
React Component
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import axios from 'axios'
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Navbar from '../layouts/navbar'
class userDashboard extends Component {
state = {
user: {}
}
getUser = () =>{
const userId = this.props.match.params.id;
axios.get(`http://localhost:5000/api/users/${userId}`).then(res=>{
const user = res.data;
this.setState({
user
})
}).catch((err)=> console.log(err))
}
componentDidMount() {
this.getUser()
}
render() {
const { name } = this.state.user
return (
<div>
<Navbar />
<h1 className="title-text">Hello { name }</h1>
</div>
);
}
}
userDashboard.propTypes = {
// logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
});
export default connect(mapStateToProps)(userDashboard);
server.js
const express = require("express");
const path = require('path');
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require('cors')
const app = express();
const users = require("./controllers/api/users")
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(`${__dirname}/client/build`));
// app.get('/*', (req, res) => {
// res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*', (req, res) => {
// res.sendFile(path.join(__dirname, '/../', 'build', 'index.html'));
// });
//DATA BASE CONFIGURATION
const dbkeys = require("./config/key").mongoURI;
mongoose.connect(
dbkeys,
{useNewUrlParser: true} )
.then(()=> console.log("database connection successful"))
.catch(err => console.log(err))
app.use(passport.initialize());
require("./config/passport")(passport);
app.use("/api/users", users);
// app.use("/api", users)
const port = 5000;
app.listen( port, () => console.log("server us up and running on port 5000!"))
Models
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork:{type: [ClassworkSchema], default: []},
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
// const User = mongoose.model('users', UserSchema);
// const Classwork = mongoose.model('Classwork', ClassworkSchema );
// module.exports = {
// User : User ,
// // Classwork : Classwork
// }
module.exports = mongoose.model("users", UserSchema);
try adding "proxy":"http://localhost:5000/" in the package.json in react
then use :
axios.get(`/api/users/${userId}`)...
I started working on a MERN App and am trying to write a restful api. Code is working fine. But POST Requests are not working.
moviemodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Movie = new Schema(
{
name: { type: String, required: true },
time: { type: [String], required: true },
rating: { type: Number, required: true },
},
{ timestamps: true },
)
module.exports = mongoose.model('users', Movie)
moviectrl.js
const Movie = require('../models/moviemodel')
createMovie = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a movie',
})
}
const movie = new Movie(body)
if (!movie) {
return res.status(400).json({ success: false, error: err })
}
movie
.save()
.then(() => {
return res.status(201).json({
success: true,
id: movie._id,
message: 'Movie created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'Movie not created!',
})
})
}
index.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
var MongoClient = require('mongodb').MongoClient;
const movieRouter = require('./routes/movierouter')
const app = express()
const apiPort = 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())
app.use(bodyParser.json())
MongoClient.connect('mongodb://127.0.0.1:27017/cinema', { useNewUrlParser:
true }, function(err, client) {
const db = client.db('cinema')
if(err) throw err;
console.log('Successfully connected')
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.use('/api', movieRouter)
app.listen(apiPort, () => console.log(`Server running on port
${apiPort}`))
movierouter.js
const express = require('express')
const MovieCtrl = require('../controllers/moviectrl')
const router = express.Router()
router.post('/movie', MovieCtrl.createMovie)
router.put('/movie/:id', MovieCtrl.updateMovie)
router.delete('/movie/:id', MovieCtrl.deleteMovie)
router.get('/movie/:id', MovieCtrl.getMovieById)
router.get('/movies', MovieCtrl.getMovies)
module.exports = router
When I send a POST Request using the link localhost:3000/api/movie and send a JSON Data through Postman. There is no response.
https://imgur.com/a/l6GvDbu
I've tested your app and found that your database is hanging ...
Replace your database connection with this 😃:
const url = 'mongodb://localhost:27017/cinema';
mongoose.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
}, console.log(`DB running on ${url}`));
https://imgur.com/gallery/q4Y0lW2
exports.createMovie = async(req,res){
try{
const create = await ModelName.create(req.body)
if(ceate){
res.send("created")
}else{
res.send("error")
}
}catch(err){
res.send(err)
}
}