stuck in : Cannot read property 'push' of undefined - javascript

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;

Related

how to fix mongoose array in node

i'm trying to push objects into my mongodb db.
I'm able to view said data when pushed in my console.log. but they arent pushed into the db at all.
Below is my app.js code..
const userSchema = new mongoose.Schema({
email : String,
password: String,
selectedPet : [String]
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
app.post("/prototype",(req, res) =>{
var animalSelected = [];
animalSelected.push = req.body.selectedPet;
console.log(req.user.id, animalSelected);
User.findById(req.user.id, function(err, foundUser){
if (err){
console.log(err);
} else {
if (foundUser){
foundUser.selectedPet = animalSelected;
foundUser.save(function(){
res.redirect("/proto")
});
}
}
});
});

Problem rendering dust template in nodejs

I keep getting this error below after posting a form using expressjs and a dust template. The form is meant to redirect after posting.
The main error lies around the router.post section it seems the problem only occurs after I try to redirect using res.redirect.
VError: Problem rendering dust template "C:\Users\USER\Desktop\nodejs\Node-Bookstore\public\templates\manage\books\add.dust": The "path" argument must be of type string. Received an instance of Chunk
at Stub.callback (C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\adaro\lib\engine.js:167:30)
at Stub.flush (C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\dustjs-linkedin\lib\dust.js:564:14)
at Chunk.setError (C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\dustjs-linkedin\lib\dust.js:1051:15)
at C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\dust-usecontent-helper\index.js:25:27
at C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\dust-makara-helpers\index.js:50:21
at C:\Users\USER\Desktop\nodejs\Node-Bookstore\node_modules\iferr\index.js:13:50
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
It only happens after res.redirect()
My code:
'use strict';
var Book = require('../models/bookmodel');
var Category = require('../models/categorymodel');
module.exports = function (router) {
router.get('/', function (req, res){
res.render('manage/index');
});
// Get Books
router.get('/books', function (req, res){
Book.find({},{}, function (err, books){
if (err){
console.log(err);
}
var model = {
books: books
}
res.render('manage/books/index', model);
});
});
// Get add book
router.get('/books/add', function (req, res){
Category.find({},{}, function (err, categories){
if (err){
console.log(err);
}
var model = {
categories: categories
}
console.log("before rendered manage/books/add");
res.render('manage/books/add', model);
});
});
//Post the details from the add books page!
router.post('/books', function (req, res){
var title = req.body.title && req.body.title.trim();
var category = req.body.category && req.body.category.trim();
var author = req.body.author && req.body.author.trim();
var publisher = req.body.publisher && req.body.publisher.trim();
var price = req.body.price && req.body.price.trim();
var description = req.body.description && req.body.description.trim();
var cover = req.body.cover && req.body.cover.trim();
if (title == '' || price == "") {
req.flash('error', 'Please input the price and title');
res.location('/manage/books/add');
res.redirect('/manage/books/add');
console.log("Empty title or price");
}
else if (isNaN(price)) {
req.flash('error', 'Price must be a number!');
res.location('/manage/books/add');
res.redirect('/manage/books/add');
console.log("price is NaN");
}else {
var newBook = new Book({
title: title,
category: category,
description: description,
author: author,
publisher: publisher,
cover: cover,
price: price,
});
newBook.save(function(err){
if (err){
console.log('save failed: ', err);
}
req.flash('success', 'New Book Added!');
res.location('/manage/books');
res.redirect('/manage/books');
console.log("was able to redirect");
});
}
});
router.get('/categories', function (req, res){
res.render('manage/categories/index');
});
};
Note: There is nothing wrong with the add.dust file
For some reason req.flash() was the issue here. Apparently I can't use the same syntax used in Jade with Dust
This will be added to the main index.js file in your root folder where you initialised the middel-ware for connect-flash
app.use(flash());
app.use(function (req, res, next) {
var messages = require('express-messages')(req, res);
res.locals.messages = function (chunk, context, bodies, params) {
return chunk.write(messages());
};
next();
});
Note that the messages function asks for (chunk, context, bodies, params) parameters and returns return chunk.write(messages());
Next:
Represent the message function with {#messages /} in your dust template

Mongoose Schema Not Defined when Route is included in different file

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

mongoose schema with dynamic nested Object

I'm trying to create a Document Schema where I would have a dynamic Object. Example:
var ModuleSchema = new Schema({
name : String,
description : String,
type : String,
age : String,
options : {}
});
Is it possible to do the
options : {}
like that? with any arbitrary attributes inside. I'm getting TypeError: Cannot read property 'find' of undefined when I try to access a route /api/something to get all the documents in the collection. It might be because of the way I've defined the schema. any ideas?
EDIT:
var Module = require('../models/module');var auth =require('../config/auth');module.exports = function(router,Module){
router
.get('/api/modules' , auth.checkAuth, function(req,res){
Module.find(function(err,modules){
if(err){
res.send(err);
}else{
res.json(modules);
}
});
})
.post('/api/modules' , auth.checkAuth,function(req,res){
var module = new Module();
console.log(req.body);
module.name = req.body.name;
module.type = req.body.type;
module.description = req.body.description;
module.age = req.body.filename;
module.options = req.body.options;
module.save(function(err,module){
if(err){
res.send(err);
}else{
res.json({ id : module._id});
}
});
});
I use something like this.
// Importing the Users Mongoose Scheme
var User = require('../app/models/user');
var Feed = require('../app/models/ufeed');
module.exports = function(app) {
// A Route to get all users info
app.get('/user/all', function(req, res) {
// use mongoose to get all users in the database
User.find(function(err, user)
{
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
{
res.send(err);
}
// return all todos in JSON format
res.json(user);
});
});
Within my server.js file I am creating an app like so.
var app = express();
And then passing it to my routes file.
require('./app/routes.js')(app); // load our routes and pass in our app
I hope this helps.

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