Mongoose Schema Not Defined when Route is included in different file - javascript

To clean up my code, I decided to put all of my schemas and routes into different files in my directory, and require them in my app.js. Each Schema corresponds to each route. For all but one of my routes, I have gotten this to work, but for one specific one, I cannot find out why I am getting it as undefined.
Here is the code I have in my app.js (the main file)
// Schemas
const Transaction = require ("./models/transaction");
User = require ("./models/user");
Ticket = require ("./models/ticket");
Job = require ("./models/job");
Client = require ("./models/client");
// Routes
require("./routes/users")(app);
require("./routes/tickets")(app);
require("./routes/clients")(app);
require("./routes/jobs")(app);
require("./routes/transactions")(app);
All of these work, except for my transaction route.
Here is its schema:
// =======================Transaction Schema "./models/transaction"
var transactionSchema = new mongoose.Schema({
job: String,
client: String,
deposited_by_user: String,
transaction_info:{
amount: mongoose.Decimal128,
method: String,
receipt_number: String,
date: {type: Date}
},
billing_address: {
street: String,
city: String,
state: String,
zip: String
},
notes: String,
date_added: {type: Date, default: Date.now}
});
module.exports = mongoose.model("Transaction", transactionSchema);
And its route:
module.exports = function(app) {
// =======================Transaction "./routes/transactions"
// index
app.get("/transactions", function(req, res){
Transaction.find({}, function(err, transactions){ // It is at this line where it is telling me that "Transaction" is undefined. However, with this code pasted into the app.js exactly the same as it is here, it works fine.
if(err){
console.log("error")
} else {
for (let i = 0; i < transactions.length; i++){
transactions[i]["transaction_info"]["new_amount"] = numberWithCommas(transactions[i]["transaction_info"]["amount"]);
}
res.render("transactions", {transactions: transactions});
}
});
});
// new
app.get("/transactions/add", async function(req, res){
let endCollections = [];
for (let i = 0; i < collections.length; i++){
await collections[i].find({}, function(err, foundCollection){
if (err) {
console.log(err);
} else {
endCollections[i] = foundCollection;
}
});
}
res.render("add_transaction", {users: endCollections[0], clients: endCollections[2], jobs: endCollections[3]});
});
// show
app.get("/transactions/:id", function(req, res){
Transaction.findById(req.params.id, function(err, foundTransaction){
if (err){
console.log(err);
} else {
// Redirect
let price = numberWithCommas(foundTransaction["transaction_info"]["amount"]);
res.render("transaction", {transaction: foundTransaction, price: price});
}
});
});
// edit
app.get("/transactions/:id/edit", function(req, res){
Transaction.findById(req.params.id, async function(err, foundTransaction){
if (err){
console.log("error")
} else {
let endCollections = [];
for (let i = 0; i < collections.length; i++){
await collections[i].find({}, function(err, foundCollection){
if (err) {
console.log(err);
} else {
endCollections[i] = foundCollection;
}
});
}
let deposit_date = foundTransaction["transaction_info"]["date"];
deposit_date = moment(deposit_date).format("MM-DD-YYYY");
res.render("edit_transaction", {transaction: foundTransaction, users: endCollections[0], clients: endCollections[2], jobs: endCollections[3], deposit_date: deposit_date});
}
});
});
// create
app.post("/transactions", function(req, res){
// Create Transaction
Transaction.create(req.body.transaction, function(err, newTransaction){
if (err){
console.log(err)
} else {
// Redirect
res.redirect("/transactions");
}
});
});
// update
app.put("/transactions/:id", function(req, res){
// Update transaction
Transaction.findByIdAndUpdate(req.params.id, req.body.transaction, function(err, updatedTransaction){
if (err){
console.log(err)
} else {
// Redirect
res.redirect("/transactions/" + req.params.id);
}
});
});
// delete
app.delete("/transactions/:id", function(req, res){
// Delete job
Job.findByIdAndRemove(req.params.id, function(err, deletedTransaction){
if (err){
console.log(err)
} else {
// Redirect
res.redirect("/transactions");
}
});
});
}
I do not believe the Schema is the problem because when I paste the Transaction route code directly into my app.js file, character for character, it works fine. However, with it split (and the code stays exactly the same in the transactions.js file) I am getting the error when I load the page that "Transaction is undefined" at the part of my code that starts with Transaction.find
Overall, I cannot understand why when the route is in the app.js file, it works just fine, but when it is in a separate file, the Transaction variable is considered undefined; this is all despite it being modeled exactely the same as my other routes and schemas. Is there something here I am not seeing? Thanks.

1)
Instead of:
app.get("/transactions", function(req, res){
.
.
app.get("/transactions/:id", function(req, res){
Maybe just:
app.get("/", function(req, res){
.
.
app.get("/:id", function(req, res){
and so on?
2)
Transaction.find({}, function(err, transactions){
Instead of {} try ()
Transaction.find((), function(err, transactions){
It looks as you are passing one empty object

Related

My second endpoint doesn't work for node-js API, why?

Trying to make my first API. It was going well, except for some reason my second route, app.route('characters/:characterId') isn't working. None of the endpoints work, even though the first route, app.route('/characters') works fine. I've been on this for like an hour and I have no idea what's going on.
Help?
Here is the controller
'use strict';
var mongoose = require('mongoose'),
Character = mongoose.model('Characters')
exports.list_all_characters = function(req, res) {
Character.find({}, function(error, character){
if (error)
res.send(error);
res.json(character)
})
}
exports.create_a_character = function(req, res) {
var new_character = new Character(req.body);
new_character.save(function(error, character){
if (error)
res.send(err);
res.json(character);
});
};
exports.get_a_character = function(req, res) {
Character.findbyId(req.params.characterId, function(error, character){
if(error)
res.send(err);
res.json(character);
});
}
exports.update_a_character = function(req, res) {
Character.findByIdAndUpdate({_id: req.params.characterId}, req.body, {new: true}, function(error){
if (error)
res.send(error);
res.json(character);
});
};
exports.delete_a_character = function(req, res) {
Character.remove({_id: req.params.characterId}, function(error, character) {
if(error) {
res.send(error);
res.json({message: 'Character Deleted'});
}
})
}
Here is the router
'use strict';
module.exports = function(app) {
var characterList = require('../controllers/characterListController')
app.route('/characters')
.get(characterList.list_all_characters)
.post(characterList.create_a_character);
app.route('characters/:characterId')
.get(characterList.get_a_character)
.put(characterList.update_a_character)
.delete(characterList.delete_a_character);
};
You are missing a /
app.route('/characters/:characterId')

stuck in : Cannot read property 'push' of undefined

This is my first project and my first post.
I'm creating a betting website to use between friends and I'm stuck with this error : Cannot read property 'push' of undefined
I guess its something small to make its work again?
Any sugestions?
router.post("/bets", function(req, res){
var betHome = req.body.betHome;
var betAway = req.body.betAway;
var matchid= "5e84bd729511b98c34101a9e"
var author = {
id: req.user._id,
username: req.user.username
}
var newBet = {bet:[betHome,betAway],author:author, matchid:matchid}
Bet.create(newBet, function (err, newlyCreated){
if(err){
console.log(err);
} else {
Match.betsList.push(newBet)
res.redirect("/bets");
console.log(newBet)
}
})
})
module.exports = router;
Database Schema
You can't push in Model directly first create an object of Match Model then push.
router.post("/bets", function(req, res){
var betHome = req.body.betHome;
var betAway = req.body.betAway;
var matchid= "5e84bd729511b98c34101a9e"
var author = {
id: req.user._id,
username: req.user.username
}
var newBet = {bet:[betHome,betAway],author:author, matchid:matchid}
Bet.create(newBet, function (err, newlyCreated){
if(err){
console.log(err);
} else {
var match = new Match({}); // new Schema
match.betsList.push(newlyCreated._id)
res.redirect("/bets");
console.log(newBet)
}
})
})
module.exports = router;

Why the data is being stored twice using mongoose?

I want to save a number of data in a property call cases. What I did was to iterate a list of data that I want to store, and then adding each data to the document's property. But the problem is that each data is being stored twice. I found a person in github who had the same issue, he said the problem was with nodemon, but I ran the sever again without nodemon and is the same problem.
Also found a question in stack saying that when a callback is applied it results in saving it twice, also the case is diferent from mine:
Why does using mongoose callback result in saving data twice?
I tried removing the callback, but I still have the same problem. (I dont think that a callback might do that)
This is the code:
var UserSchema = Schema({
user: {type: String},
password: {type: String},
name: {type: String},
privilege: {type: String},
cases: {type: Array}
})
var user = db.model('User', UserSchema , "users");
app.post("/addCases", function(req, res){
user.find({user: req.body.user}, async function(err, doc) {
if(err) {
console.log(err);
} else {
for (const iterator of req.body.list) {
await user.updateOne({user: req.body.user},
{ $push: {cases: iterator}}, {useFindAndModify: false}, function(err, raw) {
if(err) {
console.log(err);
} else {
console.log(value + ' <----- Value');
}
});
}
}
});
});
I think your problem might be related to you not ending the request in your server's code. After doing the modifications in your db, you should send a response to your front-end, if not it might try to repeat the request and you would end up with your endpoint being called two times.
Try something like:
app.post("/addCases", function(req, res){
user.find({user: req.body.user}, async function(err, doc) {
if(err) {
console.log(err);
} else {
for (const iterator of req.body.list) {
await user.updateOne({user: req.body.user},
{ $push: {cases: iterator}}, {useFindAndModify: false}, function(err, raw) {
if(err) {
console.log(err);
} else {
console.log(value + ' <----- Value');
}
});
}
}
// New code
res.json({ ok: true });
});
});

Parsing error: Unexpected token (blank)

Hi im getting Parsing error: Unexpected token with no unexpected token if that makes sense. normally it tells you which token is unexpected but not for me.
In my code it says on line x there is an unexpected ) but when i delete that ) the error just moves to the bottom of the page where there is no code and just give the same error but without mentioning what the unexpected token is.
I have looked over google for an answer but its probably somone ; or ) i have missed somewhere so i related to my code but i cant seem to find it.
Here is the code where i get the first unexpected token )
app.put("/index/new_weight", function(req,res){
Exe.findById(req.body.exercise_id, function(err, array){
if (err){
console.log(err);
res.send(err);
}else{
var value = [0];
var oldArray = array.previous;
var newArray = req.body.exe.previous;
for (var i = 0; i < newArray.length; i++){
if (newArray[i] === ""){
value.push(oldArray[i]);
}else{
value.push(newArray[i]);
}
Exe.findByIdAndUpdate(req.body.exercise_id, {$set : {"previous" : value}}, function(err, newArray){
if (err){
console.log(err);
}else{
res.redirect("/index");
}
});
}
};
}); <<<< unexpected token ) apparently...
If i remove said ) the error just moves to the bottom of the page. Same error but doesnt specify what the unexpected token is....
Here is my full code in case the error is coming from above or below. I realize im probably just missing a ) or } somewhere but i cant find.
// REQUIRE REQUIRED FRAMEWORKS AND LIBS
var express = require("express");
var mongoose = require("mongoose");
var bParser = require("body-parser");
var ejs = require("ejs");
var mOverride = require("method-override");
//INITIALIZE EXPRESS, SETUP DB AND CALL LIBS
var app = express();
mongoose.connect("mongodb://localhost/exerciseApp");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bParser.urlencoded({extended: true}));
app.use(mOverride("_method"));
//DB TEMPLATE
var exerciseSchema = new mongoose.Schema({
user: String,
exercise: [String],
previous: [Number],
latest: [Number]
});
var Exe = mongoose.model("Exe", exerciseSchema);
//**********************TESTING PURPOSES******************************
//CREATE TEST DATA
// Exe.create({
// user: "Template",
// exercise: ["Test"],
// previous: [0],
// latest: [0]
// });
// Exe.create({
// user: "Nathan",
// exercise: ["Bench Press"],
// previous: [35],
// latest: []
// });
// Exe.findOne({name: "Marc"}, function(err, test){
// console.log(test);
// });
//****************************************************
//ROUTES
app.get("/", function(req,res){
res.redirect("/index");
});
app.get("/index", function(req,res){
Exe.find({}, function(err, exercise){
if (err){
res.render("Oops, Somthing went wrong!");
}else{
res.render("index", {exes: exercise});
}
});
});
app.get("/index/new", function(req,res){
res.render("new");
});
app.put("/index", function(req,res){
Exe.update({}, {$push: req.body.exe}, {multi: true}, function(err, numAffected){ //ADDS NEW WORKOUT TO EACH USER
if (err){
console.log(err);
}else{
Exe.update({}, {$push: {"previous" : 0}}, {multi: true}, function(err, numAffected){ //PUSH STARTING VALUE OF 0 INTO PREVIOUS WEIGHT.
if (err){
console.log(err);
}else{
res.redirect("/index");
}
});
}
});
});
app.put("/index/new_weight", function(req,res){
Exe.findById(req.body.exercise_id, function(err, array){
if (err){
console.log(err);
res.send(err);
}else{
var value = [0];
var oldArray = array.previous;
var newArray = req.body.exe.previous;
for (var i = 0; i < newArray.length; i++){
if (newArray[i] === ""){
value.push(oldArray[i]);
}else{
value.push(newArray[i]);
}
Exe.findByIdAndUpdate(req.body.exercise_id, {$set : {"previous" : value}}, function(err, newArray){
if (err){
console.log(err);
}else{
res.redirect("/index");
}
});
}
});
});
app.get("/index/new/user", function(req,res){
res.render("newuser");
});
app.post("/index/new/user", function(req,res){
Exe.findOne({},{},{sort: {create_at: -1}}).lean().exec(function (err, templateSchema){ //.LEAN AND EXEC RETURNS COLLECTION MODEL AS A JS OBJECT.
if (err){
console.log(err);
res.send(err);
} else{
delete templateSchema["_id"];
templateSchema.user = req.body.exe.user;
Exe.create(templateSchema);
res.redirect("/index");
}
});
});
// SETUP SERVER AND LISTEN ON PORT.
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Excercise App Running...");
});
Thanks in advance for any answers!
Here is your code fixed, you miss a } for the for loop and a ) for the Exe.findById function
app.put("/index/new_weight", function (req, res) {
Exe.findById(req.body.exercise_id, function (err, array) {
if (err) {
console.log(err);
res.send(err);
} else {
var value = [0];
var oldArray = array.previous;
var newArray = req.body.exe.previous;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === "") {
value.push(oldArray[i]);
} else {
value.push(newArray[i]);
}
Exe.findByIdAndUpdate(req.body.exercise_id, { $set: { "previous": value } }, function (err, newArray) {
if (err) {
console.log(err);
} else {
res.redirect("/index");
}
});
}
}
});
});

ExpressJS PUT method undefined objecty issue

I am trying to use the PUT method to update a record in my database, but I am running into a issue where the object is not defined.
ReferenceError: blogpost is not defined
I am referencing this tutorial with my routing steps and noticed that despite the variable being defined in my /blogs route, meaning that it is local to that function, that in the tutorial, they don't define the variable again when routing their put method. They simply call the object's property that they plan to update. Is there a reason why I'm not able to access this object? Is it a scope issue?
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
//index
router.route('/')
.get(function(req, res) {
var drinks = [
{ name: 'Bloody Mary', drunkness: 3 },
{ name: 'Martini', drunkness: 5 },
{ name: 'Scotch', drunkness: 10}
];
var tagline = "Lets do this.";
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
//blog
router.route('/blog')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.content = req.body.content; // set the blog content
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res) {
Blogpost.find(function(err, blogs) {
if (err)
res.send(err);
res.json(blogs);
});
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
res.json(blog);
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
Specific area where the issue is created:
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
Should be:
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {

Categories