Here is my code:
//server.js
const express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
const Mate = require('./models/mate');
mongoose.Promise = global.Promise;
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27018/mate', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Mongodb db connection established succ');
})
router.route('/mate').get((req, res) => {
mongoose.model('Mate').find((err, mate) => {
if (err)
console.log(err);
else
res.json(mate);
});
});
router.route('/mate/:id').get((req, res) => {
mongoose.model('Mate').findById((err, mate) => {
if(err)
console.log(err);
else
res.json(mate);
});
});
router.route('/mate/add').post(async (req, res) => {
try {
const mate = new Mate(req.body);
await mate.save();
res.status(200).json({
'mate:': 'Added succesfully'
});
} catch (err) {
console.log(err);
res.status(400).send( 'failed to create' );
}
});
router.route('mate/update/:id').post((req, res) => {
mongoose.model(Mate).findById(req.params.id, (err, mate) =>{
if(!mate)
return next(new Error('couldnt load doc'))
else {
mate.title = req.body.title;
mate.day = req.body.day;
mate.severity = req.body.severity;
mate.status = req.body.status;
mate.save().then(mate => {
res.json('Update done');
}).catch(err => {
res.status(400).send('update failed');
});
}
});
});
router.route('mate/delete/:id').get((req, res) => {
mongoose.model(Mate).findByIdAndRemove({_id: req.params.id}, (err, mate) => {
if(err)
res.json(err);
else
res.json('Removed');
});
});
app.use('/', router);
app.listen(4000, () => console.log('server running on port 4000'));
//mate.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let MateSchema = new Schema({
title: {
type: String
},
day: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
module.export = mongoose.model('Mate', MateSchema);
So basically problem is with add controller in server.js, that must throw post request to my DB with new json created.
Well, it doesn't, but it throws this error:TypeError: Mate is not a constructor;
Help me please figure out why is it going so. I'm new at code so this may be silly question, but i'm stuck at it.
make mate.js like below
module.exports = function(mongoose) {
var options = {
collection: 'mate',
timestamps: {
createdAt: 'created_on',
updatedAt: 'updated_on'
},
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
};
let MateSchema = new mongoose.Schema({
title: {
type: String
},
day: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
return MateSchema;
};
Make changes in the module export as:
module.export = Mate = mongoose.model('Mate', MateSchema);
Related
I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};
I have a mongo model like this:-
var mongoose = require('mongoose');
const itemsModel = new mongoose.Schema({
_id: {
type: String,
},
userName: {
type: String,
required: true
},
description: {
type: String,
required: false
},
itemId: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model("itemsModel", itemsModel);
and I am handling my backend route in a file called itemRoute.js like this:-
const express = require("express");
const router = express.Router();
const id = require('uuid');
const itemsModel = require("../src/model/itemsModel");
router.post('/add-item/', (req, res) => {
const { userName, description, itemId } = req.body;
itemsModel.findOne({
itemId: itemId,
userName: userName,
}, (error, prevData) => {
if(error){
return res.send({
success: false,
description: `Internal Server Error ${error}`
});
}
if (prevData.length > 0){
itemsModel.findOneAndUpdate(
{ _id: prevData[0]._id },
{ description: description },
(error, status) => {
if (error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
} else {
return res.status(200).json({
success: true,
description: "Updated item successfully",
prevData: prevData,
status: status
});
}
}
);
}
const newModel = new itemsModel;
newModel._id = id.v4();
newModel.userName = userName;
newModel.itemId = itemId;
newModel.description = description;
newModel.save((error, user) => {
if(error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
}
return res.status(200).json({
success: true,
description: "Added item to db",
user: user
});
});
});
});
router.get('/get-items/:itemId/', (req, res) => {
console.log(req.body);
const itemId = req.params.itemId;
return res.status(200).json({
success: true,
description: "Nicee",
id: itemId,
});
});
module.exports = router;```
I have the following in my index.js express file:-
app.use('/api', require('./routes/itemRoute'));
and I am calling from my frontend like this:-
handleAddItemButton = (event) => {
event.preventDefault();
const data = {
userName: this.props.userName,
description: this.state.description,
itemId: this.props.itemId,
}
fetch(`http://localhost:8000/api/add-item/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch((err) => console.log(err));
};
My index.js file:-
/* jshint esversion:6 */
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('./build'));
app.use(express.static('./build/static'));
app.use('/api', require('./routes/auth'));
app.use('/api', require('./routes/items'));
app.use('/api', require('./routes/itemRoute'));
mongoose.set('useCreateIndex', true);
const port = 8000
mongoose.connect('mongodb://localhost:27017/item-app', {
useNewUrlParser: true
})
app.get('/*', (req, res) => {
res.sendFile(path.resolve('./build/index.html'))
})
app.listen(port, () => console.log(`server running at ${port}`));
When my frontend actually makes the request, I am thrown the following error:-
POST http://localhost:8000/api/add-item/ net::ERR_CONNECTION_REFUSED
I have looked through my code again and again but to no avail. Any and all help is sincerely appreciated. Please guide me through what Im doing wrong.
Edit 1:-
After #ewokx comment I ran mongod and got the following;-
Is this the issue? How to solve this?
MongoDB requires a data folder to store its files.
The default location for the MongoDB data directory is c:\data\db. So, create this folder it will solve your issue.
Hi so I seem to have successfully solved the problem. The problem wasn't with any of the things like db permissions, mongod, ports or something like that. I reset my index.js file to match the db name in the db connection.
Another thing I was doing wrong, I was passing a json stringified object as the request body. Removing that and on connecting proeprly to the db, the code started working nicely.
I am stuck on Test #3 and at a loss. Any help, advice or suggestions are welcome. I am using Glitch to write my code. Everything syncs up to my database which is MongoDB. Just can't pass that test and I would suspect you would need to in order to get 4, 5, and 6 done. I am new to coding, so be nice lol Thank you
https://github.com/rbill314/Exercise-Tracker-.git
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const moment = require("moment");
const shortId = require("shortid");
/*Connect to database*/
mongoose.connect(process.env.URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
if (mongoose.connection.readyState) {
console.log("Holy Crap! It Connected");
} else if (!mongoose.connection.readyState) {
console.log("WHACHA DO!!!");
}
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
/*Model*/
const userSchema = new mongoose.Schema({
_id: { type: String, required: true, default: shortId.generate },
username: { type: String, required: true },
count: { type: Number, default: 0 },
log: [
{
description: { type: String },
duration: { type: Number },
date: { type: Date }
}
]
});
const User = mongoose.model("User", userSchema);
/*Test 1: You can POST to /api/users with form data username to create a new user.
The returned response will be an object with username and _id properties.*/
app.post("/api/users", (req, res) => {
User.findOne({ username: req.body.username }, (err, foundUser) => {
if (err) return;
if (foundUser) {
res.send("Username Taken");
} else {
const newUser = new User({
username: req.body.username
});
newUser.save();
res.json({
username: req.body.username,
_id: newUser._id
});
}
});
});
/*Test 2: You can make a GET request to /api/users to get an array of all users.
Each element in the array is an object containing a user's username and _id.*/
app.get("/api/users", (req, res) => {
User.find({}, (err, users) => {
if (err) return;
res.json(users);
});
});
/*Test 3: You can POST to /api/users/:_id/exercises with form data description, duration, and optionally date.
If no date is supplied, the current date will be used.
The response returned will be the user object with the exercise fields added.*/
app.post("/api/users/:_id/exercises", (req, res) => {
const { _id, description, duration, date } = req.body || req.params;
User.findOne({ _id }, (err, userFound) => {
if (err)
return res.json({
error: "Counld not find Carmen Sandiego"
});
let exerDate = new Date();
if (req.body.date && req.body.date !== "") {
exerDate = new Date(req.body.date);
}
const exercise = {
description: description,
duration: duration,
date: exerDate
};
userFound.log.push(exercise);
userFound.count = userFound.log.length;
userFound.save((err, data) => {
if (err)
return res.json({
error: "Not letting you save today"
});
const lenOfLog = data.log.length;
let displayDate = moment(exercise.date)
.toDate()
.toDateString();
let sendData = {
username: data.username,
description: data.log[lenOfLog - 1].description,
duration: data.log[lenOfLog - 1].duration,
_id: data._id,
date: displayDate
};
res.send(sendData);
});
});
});
/*Test 4: You can make a GET request to /api/users/:_id/logs to retrieve a full exercise log of any user.
The returned response will be the user object with a log array of all the exercises added.
Each log item has the description, duration, and date properties.*/
/*Test 5: A request to a user's log (/api/users/:_id/logs) returns an object with a count
property representing the number of exercises returned.*/
/*Test 6: You can add from, to and limit parameters to a /api/users/:_id/logs request to retrieve part
of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many
logs to send back.*/
/*listener*/
const listener = app.listen(process.env.PORT || 3000, () => {
console.log("Shhhhh!!!! Spying on port " + listener.address().port);
});
//Excercise Schema
const exSchema=new Schema({
description:{
type:String,
required:true
},
duration:{
type:Number,
required:true
},
date:String
})
//User Schema
const userSchema=new Schema({
username:{
type:String,
required:true
},
log:[exSchema]
})
const User=mongoose.model("User",userSchema)
const ExModel=mongoose.model("Excercise",exSchema)
app.use(cors())
app.use(express.static('public'))
app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
//Endpoind Of user
app.route("/api/users").post(async(req,res)=>{
const{username}=req.body
const user=await User.create({username:username})
res.json(user)
}).get(async(req,res)=>{
const user=await User.find()
res.json(user)
})
//Excercise Endpoint
app.post("/api/users/:_id/exercises",async(req,res)=>{
const{description,duration,date}=req.body
const{_id}=req.params
let excercise=await ExModel.create({description,duration:parseInt(duration),date})
if(excercise.date===""){
excercise.date=new Date(Date.now()).toISOString().substr(0,10)
}
await User.findByIdAndUpdate(_id,{$push:{log:excercise} },{new:true},(err,user)=>{
let responseObj={}
responseObj["_id"]=user._id
responseObj["username"]=user.username
responseObj["date"]=new Date(excercise.date).toDateString(),
responseObj["description"]=excercise.description,
responseObj["duration"]=excercise.duration
res.json(responseObj)
})
res.json({})
})
//Logs Endpoint
app.get("/api/users/:_id/logs",async(req,res)=>{
if(req.params._id){
await User.findById(req.params._id,(err,result)=>{
if(!err){
let responseObj={}
responseObj["_id"]=result._id
responseObj["username"]=result.username
responseObj["count"]=result.log.length
if(req.query.limit){
responseObj["log"]=result.log.slice(0,req.query.limit)
}else{
responseObj["log"]=result.log.map(log=>({
description:log.description,
duration:log.duration,
date:new Date(log.date).toDateString()
}))
}
if(req.query.from||req.query.to){
let fromDate=new Date(0)
let toDate=new Date()
if(req.query.from){
fromDate=new Date(req.query.from)
}
if(req.query.to){
toDate=new Date(req.query.to)
}
fromDate=fromDate.getTime()
toDate=toDate.getTime()
responseObj["log"]=result.log.filter((session)=>{
let sessionDate=new Date(session.date).getTime()
return sessionDate>=fromDate&&sessionDate<=toDate
})
}
res.json(responseObj)
}else{
res.json({err:err})
}
})
}else{
res.json({user:"user not found with this id"})
}
})
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const { Schema } = require('mongoose')
const bodyParser = require('body-parser')
require('dotenv').config()
const MONGO_URL = process.env.MONGO_URL;
mongoose.connect(MONGO_URL);
const userSchema = new Schema ({
username: {
type: String,
required: true
},
log: [{
date: String,
duration: {type: Number,
required: true
},
description: {type: String,
required: true
},
}],
count: Number
});
const User = mongoose.model('User', userSchema); //creates new user
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
app.route('/api/users')
.post((req, res) => {
const username = req.body.username
const user = new User({ username, count: 0 })
user.save((err, data) => {
if (err) {
res.json({error: err})
}
res.json(data)
})
})
.get((req, res) => {
User.find((err, data) => {
if (data) {
res.json(data)
}
})
})
app.post('/api/users/:_id/exercises', (req, res) => {
const { description } = req.body
const duration = parseInt(req.body.duration)
const date = req.body.date ? 'Mon Jan 01 1990' : 'Thu Nov 04 2021'
const id = req.params._id
const exercise = {
date,
duration,
description,
}
User.findByIdAndUpdate(id, {
$push: { log: exercise },
$inc: {count: 1}
}, {new: true}, (err, user) => {
if (user) {
const updatedExercise = {
_id: id,
username: user.username,
...exercise
};
res.json(updatedExercise)
}
})
})
app.get('/api/users/:_id/logs', (req, res) => {
const { from, to, limit } = req.query
console.log(from, to, limit)
User.findById(req.params._id, (err, user) => {
if (user) {
if (from || to || limit) {
const logs = user.log
const filteredLogs = logs
.filter(log => {
const formattedLogDate = (new Date(log.date)).toISOString().split('T')[0]
return true
})
const slicedLogs = limit ? filteredLogs.slice(0, limit) : filteredLogs
user.log = slicedLogs
}
res.json(user)
}
})
})
app.get('/mongo-health', (req, res) => {
res.json({ status: mongoose.connection.readyState
})
})
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
I'm building a simple site that handles users using Passport.js. I can run my server but when a user submits their signup information it spits out "TypeError: Cannot read property 'create' of undefined".
I know what's happening, I just can't understand why. The error gets thrown in api-routes.js, specifically in the api/signup function when it attempts to create a user via db.User.create. When I console.log(db), the first thing in the db object is
undefined: 'C:\\Users\\LENOVO\\Desktop\\code\\Breel\\models\\user.js'
...so the user model is being exported, it's just not defined?
Any and all help you can lend me is greatly appreciated!
user.js, from my models directory:
var bcrypt = require("bcryptjs");
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
User.prototype.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
User.hook("beforeCreate", function (user) {
user.password = bcrypt.hashSync(
user.password,
bcrypt.genSaltSync(10),
null
);
});
return User;
};
index.js, from models (this and user.js are the only two files in my models directory)
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
const model = path.join(__dirname, file);
sequelize["import"];
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
api-routes.js, from my routes directory:
var db = require("../models");
var passport = require("../config/passport");
module.exports = function (app) {
app.post("/api/login", passport.authenticate("local"), function (req, res) {
res.json("/members");
});
app.post("/api/signup", function (req, res) {
console.log(req.body);
console.log(db);
db.User.create({
email: req.body.email,
password: req.body.password,
})
.then(function () {
res.redirect(307, "/api/login");
})
.catch(function (err) {
console.log(err);
res.json(err);
});
});
app.get("/logout", function (req, res) {
req.logout();
res.redirect("/");
});
app.get("/api/user_data", function (req, res) {
if (!req.user) {
res.json({});
} else {
res.json({
email: req.user.email,
id: req.user.id,
});
}
});
};
You should correct a registration process of models:
.forEach((file) => {
const modelFile = path.join(__dirname, file);
const model = sequelize['import'](modelFile)
db[model.name] = model;
})
Whenever I attempt a post method to localhost:3001/employees I get a type error Employee is not a constructor. I've defined the schema in the employee.js file and linked it up in the app.js, I'm kinda at a loss as to why its not running. Any help would be greatly appreciated!!
Employee.js
<!-- language: lang-js -->
var mongoose = require("mongoose");
var EmployeeSchema = new mongoose.Schema({
_id: {
type: Number,
required: true
},
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
title: {
type: String,
required: true
},
start_date: {
type: String,
required: true
},
birth_date: {
type: Number,
required: true
},
wage: {
type: String,
required: true
}
})
var Employee = mongoose.model("Employee", EmployeeSchema);
module.exports = Employee;
<!-- end snippet -->
employees.js
<!-- language: lang-js -->
var express = require("express");
var mongodb = require("mongodb");
var app = express();
var router = express.Router();
var mongoose = require("mongoose");
var Employee = mongoose.model("Employee");
router.post("/", (req,res) => {
var Employee = new Employee({
_id: req.body._id,
first_name: req.body.first_name,
last_name: req.body.last_name,
title: req.body.title,
start_date: req.body.start_date,
birth_date: req.body.birth_date,
wage: req.body.wage
})
Employee.save((err, result) => {
if(err) {
res.send(err);
} else {
res.send(result);
}
})
})
router.get("/", (req, res) => {
Employee.find(function (err, employees) {
if (err) {
res.send(err);
} else {
res.send(employees);
}
})
})
router.get("/:id", (req, res) => {
var employeeid = new mongodb.ObjectID(req.params["id"]);
Employee.find({"_id": employeeid},function (err, employees) {
if (err) {
res.send(err);
} else {
res.send(employees);
}
})
})
router.put("/", (req, res) => {
var employeeid = new mongodb.ObjectID(req.params["id"]);
Employee.find({"_id": employeeid},function (err, employees) {
if (err) {
res.status(500).send(err);
} else {
employee.title = req.body.title || employee.title;
employee.description = req.body.description || employee.description;
employee.price = req.body.price || employee.price;
employee.completed = req.body.completed || employee.completed;
Employee.save(function (err, employee) {
if (err) {
res.status(500).send(err)
}
res.send(employee);
});
}
});
})
router.delete("/:id", (req, res) => {
var employeeid = new mongodb.ObjectID(req.params["id"]);
Employee.remove({_id: employeeid}).then(() => {
res.send("success");
})
})
module.exports = router;
<!-- end snippet -->
app.js
<!-- language: lang-js -->
var express = require("express");
var bodyParser = require("body-parser");
var lessMiddleware = require('less-middleware');
var mongoose = require('mongoose');
var port = 3001;
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
require("./Employee");
require("./user");
var employees = require("./employees.js");
var users = require("./users.js");
mongoose.connect("mongodb://kenth56:123#ds034807.mlab.com:34807/database_baby", {
useMongoClient: true
}).then(() => {
console.log("db connected");
}, ((err) => {
console.log(err);
}))
app.use(bodyParser.json());
app.set("view engine", "ejs");
app.use(lessMiddleware(path));
app.use(express.static(path));
app.use("/",router);
router.get("/", (req,res) => {
res.sendFile(path + "index.html");
})
app.use("/employees", employees);
app.use("/users", users);
app.listen(port, () => {
console.log("Live at Port " + port);
})
router.use( (req,res,next) => {
console.log("/" + req.method);
next();
})
app.use("*", (req,res) => {
res.sendFile(path + "404.html");
})
<!-- end snippet -->
The reason is most likely because you are declaring var Employee and that overwrites the other declaration you have for Employee. Try var e = new Employee() instead.