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)
})
Related
I´m trying to set up a register and login server with node.js and mongoose. So I have create an user model and an user route. Can someone find the mistake why I can´t create an user. I connect to Postman under POST : localhost:3000/users/register
my user model:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true, //calls .trim() on the value to get rid of whitespace
unique: true, //note that the unique option is not a validator; we use mongoose-unique-validator to enforce it
},
password: {
type: String,
required: true,
minlength: 8,
},
});
//this enforces emails to be unique!
UserSchema.plugin(uniqueValidator);
//this function will be called before a document is saved
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('password')) {
return next();
}
//we generate the salt using 12 rounds and then use that salt with the received password string to generate our hash
bcrypt
.genSalt(12)
.then((salt) => {
return bcrypt.hash(user.password, salt);
})
.then((hash) => {
user.password = hash;
next();
})
.catch((err) => next(err));
});
module.exports = mongoose.model('User', UserSchema);
my routes user:
const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const router = express.Router();
//util function to check if a string is a valid email address
const isEmail = (email) => {
if (typeof email !== 'string') {
return false;
}
const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
return emailRegex.test(email);
};
router.post('/register', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
throw new Error('Email must be a valid email address.');
}
if (typeof password !== 'string') {
throw new Error('Password must be a string.');
}
const user = new User({ email, password });
const persistedUser = await user.save();
res.status(201).json({
title: 'User Registration Successful',
detail: 'Successfully registered new user',
});
} catch (err) {
res.status(400).json({
errors: [
{
title: 'Registration Error',
detail: 'Something went wrong during registration process.',
errorMessage: err.message,
},
],
});
}
});
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!isEmail(email)) {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Email must be a valid email address',
},
],
});
}
if (typeof password !== 'string') {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Password must be a string',
},
],
});
}
//queries database to find a user with the received email
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
//using bcrypt to compare passwords
const passwordValidated = await bcrypt.compare(password, user.password);
if (!passwordValidated) {
throw new Error();
}
res.json({
title: 'Login Successful',
detail: 'Successfully validated user credentials',
});
} catch (err) {
res.status(401).json({
errors: [
{
title: 'Invalid Credentials',
detail: 'Check email and password combination',
errorMessage: err.message,
},
],
});
}
});
module.exports = router;
my server :
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const app = express();
dotenv.config();
//other imports
const usersRoute = require('./routes/users');
//other app.use statements
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true,
useUnifiedTopology: true},
() => console.log('Database connected')
);
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
//sets up the middleware for parsing the bodies and cookies off of the requests
app.use(bodyParser.json());
app.use(cookieParser());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = { app };
what I only get is this.:
Cannot POST /users/register
You didn't specify the path prefix in your server file. You should define:
app.use("/users", usersRoute );
I have three schemas.
User.js:
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
});
userSchema.pre("save", function (next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (candidatePassword) {
const user = this;
return new Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, user.password, (err, isMatch) => {
if (err) {
return reject(err);
}
if (!isMatch) {
return reject(false);
}
resolve(true);
});
});
};
mongoose.model("User", userSchema);
Project.js:
const mongoose = require("mongoose");
const diamondSchema = new mongoose.Schema({
criteria: {
novelty: String,
technology: String,
complexity: String,
pace: String,
},
});
const projectSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
projectName: {
type: String,
default: "",
},
projectBudget: {
type: Number,
},
projectDuration: {
type: Number,
},
industry: {
type: String,
},
companyName: {
type: String,
},
numberOfEmployees: {
type: Number,
},
diamond: [diamondSchema],
});
mongoose.model("Project", projectSchema);
Recommendation.js:
const mongoose = require("mongoose");
const diamondSchema = new mongoose.Schema({
criteria: {
novelty: String,
technology: String,
complexity: String,
pace: String,
},
});
const recommendationSchema = new mongoose.Schema({
diamond: [diamondSchema],
description: {
type: String,
},
});
mongoose.model("Recommendation", recommendationSchema);
And two route files.
authRoutes.js:
const express = require("express");
const mongoose = require("mongoose");
const User = mongoose.model("User");
const jwt = require("jsonwebtoken");
const router = express.Router();
router.post("/signup", async (req, res) => {
const { name, email, password } = req.body;
try {
const user = new User({ name, email, password });
await user.save();
const token =
//token has payload-->user id
jwt.sign({ userId: user._id }, "MY_SECRET_KEY");
res.send({ token });
} catch (err) {
//invalid data
return res.status(422).send(err.message);
}
});
router.post("/signin", async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(422).send({ error: "Must provide email and password" });
}
const user = await User.findOne({ email });
if (!user) {
return res.status(404).send({ error: "Invalid email or password" });
}
try {
await user.comparePassword(password);
const token = jwt.sign({ userId: user._id }, "MY_SECRET_KEY");
res.send({ token });
} catch (err) {
return res.status(422).send({ error: "Invalid email or password" });
}
});
module.exports = router;
projectRoutes.js:
const express = require("express");
const mongoose = require("mongoose");
const requireAuth = require("../middlewares/requireAuth");
const Project = mongoose.model("Project");
const Recommendation = mongoose.model("Recommendation");
const router = express.Router();
router.use(requireAuth);
router.get("/projects", async (req, res) => {
const projects = await Project.find({ userId: req.user._id });
res.send(projects);
});
router.post("/projects", async (req, res) => {
const {
projectName,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
} = req.body;
if (
!projectName ||
!projectBudget ||
!projectDuration ||
!industry ||
!companyName ||
!numberOfEmployees ||
!diamond
) {
return res.status(422).send({ error: "Must provide all project details" });
}
try {
const project = new Project({
projectName,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
userId: req.user._id,
});
await project.save();
//res.send(project);
} catch (err) {
res.status(422).send({ error: err.message });
}
try {
const rec = await Recommendation.find({ diamond });
//console.log(diamond);
console.log(description);
res.send(rec);
} catch (err1) {
res.status(422).send({ error: err1.message });
}
});
module.exports = router;
Using postman, in the projectRoutes.js file, when I try to send the post request on
localhost:3000/projects, I am trying to create a new project and in response I want description. My logic is that, after I save the new project in projects collection, I am trying to find the document with the SAME DIAMOND OBJECT criteria in recommendations collection which is also present in projects collection. Meaning, I have pre-defined records in recommendations collection and projects collection::
So I need some way so that when I try to add a new project for a user, the criteria object in diamond array I set matches to the criteria object in diamond array in pre-defined one of recommendations documents and in the post request localhost:3000/projects I can return description in response. As I'm doing console.log(description) in projectRoutes.js, it's showing as undefined. I don't know why. Hope it makes sense.
Basically, the idea is there will be limited number of recommendations with unique criterias. So whenever a new project is created based on the criteria, a recommendation is displayed to the user.
Assuming you have only one array element in a project and in an a recommendation
const {
projectName,
projectBudget,
projectDuration,
industry,
companyName,
numberOfEmployees,
diamond,
} = req.body;
const [projectDiamond] = diamond // get the first object in the diamond array
const { criteria } = projectDiamond // extract criteria
const recommendation = await Recommendation.find({ 'diamond.criteria': criteria });
Please note that the order of criteria fields must match, since we are looking up a matching object in an array.
Reference: https://docs.mongodb.com/manual/tutorial/query-arrays/#query-an-array
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);
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.
I have the following files. I have a recipe.js file which outlines the Mongoose Schema for a recipe and the comments for a recipe. The code for it goes as follows:
const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');
let Schema = mongoose.Schema;
let commentSchema = Schema({
rating: {
type: Number,
// required: true,
min: 1,
max: 5,
},
recipeItem: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Recipe'
},
comment: {
type: String,
// required: true
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
likedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
favouredBy: {
type: mongoose.Schema.Types.ObjectId
}
});
let Comment = mongoose.model('Comment', commentSchema);
let recipeSchema = Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
required: true
},
comments: [commentSchema],
category: {
type: String,
required: true,
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
module.exports = Comment;
/// refactor this so that these are in the router, not in the models file
/*
module.exports.getRecipeByName = (name, callback) => {
let nameQuery = {name: name};
Recipe.findOne(nameQuery, callback);
};
module.exports.getRecipesByCategory = (category, callback) => {
Recipe.find({'category': category});
};
*/
I also have a user.js file where I outline a a User model and the relation it has to the other models/schemas. The code in the file is as follows:
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
const passport = require('passport');
let Schema = mongoose.Schema;
let User = Schema({
name: {
type: String
},
// The passport plugin already inputs username and password into our Schema
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true,
},
profilePic: {
type: String
},
email: {
type: String,
unique: true,
required: true
},
admin: {
type: Boolean,
defualt: false
},
usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],
userComments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],
usersFavouriteRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}],
usersLikedRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]
});
let options = ({missingPasswordError: "Incorrect password, try again"});
User.plugin(passportLocalMongoose, options);
module.exports = mongoose.model('User', User);
And here is recipeRouter.js, the file where I define all the HTTP requests and routes:
const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const verification = require('../verification');
const Comment = require('../models/recipe');
// I temporarily removed verification.checkIfUserExists to see if all this database stuff works
router = express.Router();
router.use(bodyParser.json());
router.get('/', (req, res) => {
res.json('Here are the recipes!')
});
router.get('/showrecipes', (req, res) => {
Recipe.find({}).populate('Comment').exec((err, recipes) => {
if (err) throw err;
res.json(recipes);
})
});
router.get("/showrecipes/:recipeId", (req, res) => {
let nameQuery = {_id: req.params.recipeId};
Recipe.findOne(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
})
//// Don't know if this is correct
.populate('comment.recipeItem');
});
router.get('/showrecipes/category/:categoryname', (req, res) => {
let nameQuery = {category: req.params.categoryname};
Recipe.find(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
});
});
router.post('/addrecipe', (req, res, next) => {
Recipe.create({
name: req.body.name,
description: req.body.description,
steps: req.body.steps,
ingredients: req.body.ingredients,
category: req.body.category
}, (err, recipes) => {
if (err) throw err;
res.json(recipes);
});
});
// See if this works
router.put("/showrecipes/:recipeId", (req, res) => {
let query = {_id: req.params.recipeId};
Recipe.findByIdAndUpdate(query, {
$set: req.body
}, {
new: true
}, (err, recipe) => {
if (err) throw err;
res.json(recipe)
})
});
router.delete("/showrecipes/:recipeId", (req, res) => {
let query = {_id: req.params.recipeId};
Recipe.findByIdAndRemove(query, (err, recipe) => {
if (err) throw err;
res.send('Recipe was succesfully deleted');
})
});
router.get("/showrecipes/:recipeId", (req, res) => {
let nameQuery = {_id: req.params.recipeId};
Recipe.findOne(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
})
.populate('comments')
.exec((err) => {
if (err) throw err;
})
});
router.post("/showrecipes:/:recipeId/addcomment", (req, res, next) => {
Comment.create({
rating: req.body.rating,
comment: req.body.comment,
postedBy: postedBy,
date: Date.now(),
recipeItem: recipeId
})
});
router.get('/showrecipes/byuser/:username', (req, res) => {
let query = {postedBy: req.params.username};
Recipe.find(query, (err, recipes) => {
if (err) throw err;
res.json(recipes)
})
});
module.exports = router;
Now, at some point I was able to create recipes and store them in my database without a problem. But now this weird thing happens.
Here, I make my post request as you can see in the screenshot below:
But for some strange reason, everytime I make a get request, none of the key/value pairs I specified in my json body request are there. Each recipe object now only as the _id in it.
Can anyone help me? This just seems so weird.
Looks like you're simply missing the application/json Content-Type header.
In Postman, just set the header, as shown in this gif.