When I try to run my code in the browser using: http://localhost:3000/contact-list I keep getting a TypeError: User.find is not a function.
I'm working on a project that uses Ejs, MongoDB and Node.
This is the code I have written in my user-contact.js file inside my controllers folder:
let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
// Create a reference to the model
let User = require('../models/user');
module.exports.displayUserList = (req, res, next) => {
User.find((err, userList) => {
if(err) {
return console.error(err);
} else {
res.render('user/list', {title: 'Business Contacts', UserList: userList, displayName: req.user ? req.user.displayName : ''});
}
}) .sort({name: 1});
};
module.exports.displayAddPage = (req, res, next) => {
res.render('user/add', {title: 'Add New Contact', displayName: req.user ? req.user.displayName : ''});
};
module.exports.processAddPage = (req, res, next) => {
let newUser = User({
"name": req.body.name,
"number": req.body.number,
"email": req.body.email
});
User.create(newUser, (err, User) => {
if(err) {
console.log(err);
res.end(err);
} else {
// Refresh the Contact List
res.redirect('/contact-list');
}
});
};
module.exports.displayEditPage = (req, res, next) => {
let id = req.params.id;
User.findById(id, (err, userToEdit) => {
if(err){
console.log(err);
res.end(err);
} else {
// Show the Edit view
res.render('user/edit', {title: 'Update Contacts', user: userToEdit, displayName: req.user ? req.user.displayName : ''});
}
});
};
module.exports.processEditPage = (req, res, next) => {
let id = req.params.id;
let updatedUser = User({
"_id": id,
"name": req.body.name,
"number": req.body.number,
"email": req.body.email
});
User.updateOne({_id: id}, updatedUser, (err) => {
if(err) {
console.log(err);
res.end(err);
} else {
// Refresh the Contact List
res.redirect('/contact-list');
}
});
};
module.exports.performDelete = (req, res, next) => {
let id = req.params.id;
User.remove({_id: id}, (err) => {
if(err) {
console.log(err);
res.end(err);
} else {
// Refresh the Contact List
res.redirect('/contact-list');
}
});
};
The output should show the contact-list information. Instead, I'm getting an error that User.find is not a function, but I clearly have it inside a function.
I would really appreciate if someone could help me out.
I have a nodeJs application which is working fine with one schema from MSSQL, but i have a requirement where i need to use another schema and do some api calls.
first API is working fine and giving out result.
But when I tried with another get api named "/stockOrderDetails" it is just giving empty data like this:
Can anyone please let me know how to use different schemas in a single JS file for nodeJS
{
"code": 200,
"status": "OK",
"message": "Data Operation Success",
"data": {
"orderDetail": [
]
}
}
Here is my actual code:
const express = require("express");
var sql = require("mssql");
const { json, urlencoded } = require("body-parser");
const multer = require("multer");
var config = {
user: "jsudjac",
password: "********",
server: "********",
database: "JSULLC_Test",
};
var dataSource = {
user: "jsudjac",
password: "*****",
server: "*********",
database: "Stock_Test",
};
const dbconn1 = sql.connect(config, (err) => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing");
}
});
const dbconn2 = sql.connect(dataSource, (err) => {
if (!err) {
console.log("connected");
} else {
console.log(err);
}
});
const storage = multer.diskStorage({
destination: "./uploads",
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const app = express();
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
const upload = multer({
storage: storage,
dest: "./uploads/",
}).single("file");
app.use(json());
app.use(urlencoded({ extended: true }));
app.get("/jsuOrderDetails/:jsuOrder", (req, res) => {
const request = new sql.Request(dbconn1);
request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
request.execute("mobile_getOrderDetails", (err, result) => {
if (!err) {
var out = {
code: 200,
status: "OK",
message: "Data Operation Success",
data: {
orderDetail: result.recordsets[0],
},
};
} else {
var out = {
status: 404,
data: {},
};
}
res.send(out);
});
});
app.get("/stockOrderDetails/:jsuOrder", (req, res) => {
const request = new sql.Request(dbconn2);
console.log("hithithit");
request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
console.log(req.params.jsuOrder);
request.execute("mobile_getOrderDetails", (err, result) => {
if (!err) {
var out = {
code: 200,
status: "OK",
message: "Data Operation Success",
data: {
orderDetail: result.recordsets[0],
},
};
} else {
var out = {
status: 404,
data: {},
};
}
res.send(out);
});
});
app.get("/validate", (req, res) => {
let query = "select * from ma_smallpipe_coating_details";
console.log("hithit");
dbconn2.query(query, (err, rows) => {
if (!err) {
console.log(rows.recordsets[0]);
}
});
});```
Edit: Thanks for your help everyone. I ended up completely rewriting the code using async await to be more readable. The issue no longer persists.
I've been getting the following error when I try to view my site's ecommerce cart at /cart:
Example app listening on port 8080
/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongodb/lib/utils.js:132
throw err;
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:500:11)
at ServerResponse.setHeader (_http_outgoing.js:507:3)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/controllers/cart.js:99:9
at Function.<anonymous> (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:3928:16)
at parallel (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:2078:12)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/parallel.js:35:9
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/once.js:12:16
at iteratorCallback (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/eachOf.js:52:13)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/onlyOnce.js:12:16
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/parallel.js:32:13
at apply (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/lodash/_apply.js:15:25)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/lodash/_overRest.js:32:12
at callbackWrapper (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:2047:11)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:3928:16
at model.$__save.error (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:343:7)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/kareem/index.js:297:21
This error seems to be caused by the lines:
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
After looking at some similar issues, I am fairly sure the lines above are comming into conflict with these:
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
However, I'm not sure how to fix this issue and could be wrong.
Here's my full cart code:
module.exports = function(app){
// Dependencies and imported functions
const async = require('async');
const ObjectId = require('mongoose').Types.ObjectId;
const validate = require('../modules/validate');
const paypal = require('paypal-rest-sdk');
const cookie = require('cookie');
const path = require('path');
const appDir = path.dirname(require.main.filename);
const cartMod = require("../modules/cart");
const cartCount = cartMod.itemCount;
const crypto = require("crypto");
// DB
const Cart = require('../models/carts');
const CartItem = require('../models/cart_items');
const Discount = require('../models/discounts');
const Product = require('../models/products');
paypal.configure({
"host" : "api.sandbox.paypal.com",
"port" : "",
'mode': 'sandbox', //sandbox or live
'client_id': process.env.JSC_PAYPAL_CLIENT_ID,
'client_secret': process.env.JSC_PAYPAL_CLIENT_SECRET
});
const payPalPayment = (items, total) => {
return {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": appDir + "/success",
"cancel_url": appDir + "/cancel"
},
"transactions": [{
"item_list": { "items": items },
"amount": {
"currency": "USD",
"total": total
},
"description": "This is the payment description."
}]
};
};
const createPayPalPayment = (payment, req, res) => {
paypal.payment.create(payment, function(err, payment) {
if (err) {
throw err;
} else {
if(payment.payer.payment_method === 'paypal') {
req.paymentId = payment.id;
var redirectUrl;
for(var i = 0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
}
});
};
const displayCartItems = (res, cartId, cartCount, discount) => {
CartItem.find({cart: cartId}, function(err, cartItems) {
if (err) return next(err);
var products = [];
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) throw err;
products.push(product);
return next();
});
},
function(err) {
if (err) res.status(400).send("Could not display cart items");
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
}
);
});
};
const createCart = (req, res, next) => {
var token = crypto.randomBytes(20).toString("hex");
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
return next();
});
};
const checkCart = (req, res, next) => {
var token = req.cookies["cart_token"];
if (!token) {
createCart(res, res, next);
} else {
Cart.find({token: token}, function(err, cart) {
if (err || !cart) createCart(res, res, next);
return next();
});
}
};
const addCartItem = (cartId, productId, quantity) => {
CartItem.findOne(
{'product': productId, "cart": cartId},
function(err, item) {
if (err || !item) {
CartItem.create({
cart: cartId,
product: productId,
quantity: quantity
});
} else {
var newQuantity = item.quantity + parseInt(quantity);
CartItem.update(
{'_id': item._id},
{quantity: newQuantity},
function(err, item) {});
}
}
);
};
const updateCartItem = (res, id, quantity) => {
CartItem.findById(id, function(err, item) {
if (err || !item) throw err;
CartItem.update({_id: id}, {quantity: quantity}, function(err, item) {
res.send("Successfully updated cart item quantity.");
});
});
};
const deleteCartItem = (res, id) => {
CartItem.findById(id, function(err, item) {
if (err || !item) throw err;
CartItem.remove({_id: id}, function(err, item) {
res.send("Successfully deleted cart item.");
});
});
};
const cartIndex = (req, res, cartCount) => {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) throw err;
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
displayCartItems(res, cart._id, discount.percent, cartCount);
});
} else {
displayCartItems(res, cart._id, 0, cartCount);
}
});
};
app.get("/discount", function (req, res) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {cartCount: cartCount});
});
});
app.post("/discount", checkCart, function (req, res) {
var code = req.body["code"];
Discount.findOne({code: code}, function(err, discount) {
if (err || !discount) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {err: true, cartCount: cartCount});
});
} else {
var cartToken = req.cookies["cart_token"];
Cart.findOne({token: cartToken}, function(err, cart) {
if (err || !cart) throw err;
Cart.update(
{_id: cart._id},
{discount: discount._id},
function(err, cart) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {err: false, cartCount: cartCount});
});
}
);
});
}
});
});
app.get('/cart', checkCart, function (req, res, next) {
cartCount(req, res, cartIndex);
});
app.post('/cart', checkCart, function (req, res, next) {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) return next(err);
CartItem.find({cart: cart._id}, function(err, cartItems) {
if (err) return next(err);
var purchases = [];
var total = 0;
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) {
res.status(400).send("Could not find products");
} else {
var purchase = {};
purchase["name"] = product.name;
purchase["sku"] = product.name;
purchase["price"] = product.price;
purchase["currency"] = "USD";
purchase["quantity"] = cartItem.quantity;
purchases.push(purchase);
total += product.price * cartItem.quantity;
}
return next();
});
},
function(err) {
if (err) {
res.status(400).send("Could not display cart items");
} else {
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
var discountItem = {};
discountItem["name"] = "Discount";
discountItem["sku"] = "Discount";
discountItem["price"] = -1 * (total * discount.percent / 100);
discountItem["currency"] = "USD";
discountItem["quantity"] = 1;
purchases.push(discountItem);
total += discountItem.price;
var payment = payPalPayment(purchases, total);
createPayPalPayment(payment, req, res);
});
} else {
var payment = payPalPayment(purchases, total);
createPayPalPayment(payment, req, res);
}
}
}
);
});
});
});
app.post('/cart/confirm', checkCart, function (req, res, next) {
var cartToken = req.cookies["cart_token"];
Cart.find({token: cartToken}, function(err, cart) {
if (err || !cart) return next(err);
else {
CartItem.find({cart: cart._id}, function(err, cartItems) {
if (err) return next(err);
var products = [];
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) {
res.status(400).send("Could not find products");
} else {
products.push(product);
}
return next();
});
},
function(err) {
if (err) {
res.status(400).send("Could not display cart items");
} else {
executePayPalPayment(req);
res.render("cart/index", {
cartItems: cartItems,
products: products
});
}
}
);
});
}
});
});
app.post('/cart/add/:id', checkCart, function (req, res, next) {
var cartToken = req.cookies["cart_token"];
var productId = req.params.id;
var quantity = validate.sanitize(req.body[`quantity`]);
if (validate.isInt(quantity)) {
Product.findById(productId, function(err, product) {
if (err || !product) throw err;
Cart.findOne({token: cartToken}, function(err, cart) {
if (err || !cart) throw err;
addCartItem(cart._id, product._id, quantity);
res.send("Product added!")
});
});
}
});
app.post('/cart/update/:id', checkCart, function (req, res, next) {
var id = req.params.id;
var quantity = req.body["quantity"];
if (!validate.isInt(quantity)) throw err;
else if (quantity < 1) {
deleteCartItem(res, id);
} else {
updateCartItem(res, id, quantity);
}
});
app.post('/cart/delete/:id', checkCart, function (req, res, next) {
var id = req.params.id;
deleteCartItem(res, id);
});
}
const createCart = (req, res, next) => {
var token = crypto.randomBytes(20).toString("hex");
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
return next();
});
};
const cartIndex = (req, res, cartCount) => {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) throw err;
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
displayCartItems(res, cart._id, discount.percent, cartCount);
});
} else {
displayCartItems(res, cart._id, 0, cartCount);
}
});
};
app.get('/cart', checkCart, function (req, res, next) {
cartCount(req, res, cartIndex);
});
}
Essentially, I'm trying to check if the user has any cookies which could identify their cart and create a new cookie/cart if not. Also, I call cartCount to display the number of cart items at the top of each page.
I really appreciate any help! Please let me know if you need more information!
Edit:
Full app.js:
// Dependencies
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const path = require("path");
const pug = require("pug");
const session = require("express-session");
const validate = require("./modules/validate");
const cartMod = require("./modules/cart");
const cartCount = cartMod.itemCount;
const port = process.env.PORT || 8080;
// DB
const mongoURI = 'mongodb://localhost/db';
mongoose.connect(process.env.MONGODB_URI || mongoURI);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
// Connected!
});
app.set('trust proxy', 1)
app.set("views", __dirname + "/views");
app.set("view engine", "pug");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(__dirname + "/assets"));
app.use(session({
secret: process.env.JSC_SESSIONS_SECRET,
resave: true,
saveUninitialized: false
}));
// Routes
require("./controllers/cart")(app);
require("./controllers/categories")(app);
require("./controllers/discount")(app);
require("./controllers/nav_pages")(app);
require("./controllers/pages")(app);
require("./controllers/products")(app);
require("./controllers/users")(app);
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
cartCount(req, res, function(req, res, cartCount) {
res.render("errors/404", { cartCount: cartCount, url: req.url });
return;
});
}
});
app.listen(port, function() {
console.log("Example app listening on port " + port)
});
Add return if err or cart not exist in checkCart:
if (err || !cart) return createCart(res, res, next);
return next();
This error usually means that you called res.send() or res.end() or any of the methods that send a response to the frontend. These methods can only be called once, and after calling them you're expected not to interact with the response anymore (for example, you can't call res.setHeader if before that you called res.render.
This code:
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) throw err;
products.push(product);
return next();
});
},
function(err) {
if (err) res.status(400).send("Could not display cart items");
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
}
);
If there's an error (and res.render is fired), then you should not send information to the client anymore (because you already did). It looks like it failed for one of the cart items but you still keep interacting with the res object.
To fix the issue, avoid calling res after you've sent data to the client.
I have declare the variable first. but if I do console.log(userinsertData) outside looping variable still not fill.
what i should do for solving this problem?
here my code:
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
try {
data.forEach(function(item, index) {
var userdata = new User();
userdata.name = item.name;
userdata.age = item.age;
userdata.sex = item.sex;
userdata.save(function(err, data) {
if (err) {
res.send(err)
} else {
userinsertData.push(data);
}
});
})
} catch (e) {
res.json({
message: 'data not valid'
})
}
console.log(userinsertData);
res.json({
message: 'musician created!',
data: userinsertData
});
}
};
you should solve the problem as
async.eachSeries(data, function (info, callback) {
//here process your data and call callback() for next iteration
}, function (err) {
if (err) {
//this will be called after all iterations and in case of error
}else{
console.log('Well done :-!');
//this will be called after all interations successfully
}
});
this problem you are facing is because of asynchronous nature of nodejs and async helps you to introduce blocking.
Don't forget to include async
Use promise
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
new Promise(function(resolve, reject) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, reject
if(err) return reject(err);
// we have proceed all items in data, resolve it
else if(data.length - 1 === index) return resolve(userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}).then(function(successResult) {
res.json({
message: 'musician created!',
data: successResult
});
}, function(errorResult) {
res.json({
message: 'data not valid'
});
});
}
};
Use callbacks
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
function saveUser(callback) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, return callback with error
if(err) return callback(err);
// we have proceed all items in data, return data
else if(data.length - 1 === index) callback(null, userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}
saveUser(function(err, users) {
if(err) return res.json({message: 'data not valid'});
res.json({
message: 'musician created!',
data: users
});
});
}
};
This is what async package does internally
So i am creating a RESTFul api for my application using Node.js
However it is starting to feel abit redundant and therefore i am wondering if i am doing it correctly.
So when ever i have a new model i do the following:
First i create a file equal to the table name in the database (lets take a table called team as an example):
// IMPORT ROUTES
// =============================================================================
module.exports = function (express, sequelize, router) {
router.route('/team');
var DataTypes = require("sequelize");
var crypto = require('crypto');
// on routes that end in /Teams
// ----------------------------------------------------
router.route('/api/team')
// create a Team (accessed at POST http://localhost:8080/api/Teams)
.post(function (req, res) {
var name = req.body.name; //bodyParser does the magic
var academy_id = req.body.academy_id;
var team = Team.build({name: name, academy_id: academy_id});
team.add(function (success) {
res.json({message: 'Team created!'});
},
function (err) {
res.status(err).send(err);
});
})
// get all the Teams (accessed at GET http://localhost:8080/api/Teams)
.get(function (req, res) {
var team = Team.build();
team.retrieveAll(function (Teams) {
if (Teams) {
res.json(Teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.status("Team not found").send('Team not found');
});
});
var Team = sequelize.define('team', {
id: DataTypes.INTEGER,
name: DataTypes.STRING,
academy_id: DataTypes.INTEGER
}, {
freezeTableName: true,
instanceMethods: {
retrieveAll: function (onSuccess, onError) {
Team.findAll({}, {raw: true})
.ok(onSuccess).error(onError);
},
retrieveById: function (Team_id, onSuccess, onError) {
Team.find({where: {id: Team_id}}, {raw: true})
.success(onSuccess).error(onError);
},
add: function (onSuccess, onError) {
var Teamname = this.name;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
Team.build({name: Teamname, name: password})
.save().ok(onSuccess).error(onError);
},
updateById: function (Team_id, onSuccess, onError) {
var id = Team_id;
var Teamname = this.Teamname;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
Team.update({Teamname: Teamname, password: password}, {where: {id: id}})
.success(onSuccess).error(onError);
},
removeById: function (Team_id, onSuccess, onError) {
Team.destroy({where: {id: Team_id}}).success(onSuccess).error(onError);
},
retrieveByAcademyId: function(academy_id, onSuccess, onError)
{
Team.findAll({where: {academy_id: academy_id}}, {raw: true})
.ok(onSuccess).error(onError);
}
}
}
),
academy = sequelize.define('academy', {
id: DataTypes.INTEGER,
name: DataTypes.STRING,
organization_id: DataTypes.INTEGER,
status_id: DataTypes.INTEGER
});
Team.belongsTo(academy,{foreignKey: 'academy_id'});
// on routes that end in /Teams/:Team_id
// ----------------------------------------------------
router.route('/api/team/:team_id')
// update a Team (accessed at PUT http://localhost:8080/api/Teams/:Team_id)
.put(function (req, res) {
var team = Team.build();
team.name = req.body.name;
team.academy_id = req.body.academy_id;
team.updateById(req.params.id, function (success) {
console.log(success);
if (success) {
res.json({message: 'Team updated!'});
} else {
res.send(401, "Team not found");
}
}, function (error) {
res.send("Team not found");
});
})
// get a Team by id(accessed at GET http://localhost:8080/api/Teams/:Team_id)
.get(function (req, res) {
var team = Team.build();
team.retrieveById(req.params.team_id, function (teams) {
if (teams) {
res.json(teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
})
// delete a Team by id (accessed at DELETE http://localhost:8080/api/Teams/:Team_id)
.delete(function (req, res) {
var team = Team.build();
team.removeById(req.params.id, function (teams) {
if (teams) {
res.json({message: 'Team removed!'});
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
});
router.route('/api/academyTeam/:academy_id')
.get(function (req, res) {
var team = Team.build();
team.retrieveByAcademyId(req.params.academy_id, function (teams) {
if (teams) {
res.json(teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
});
return router;
};
Then afterwards i add the following line to my server.js:
app.use(team_model);
then i repeat the action for the next table.
Am i doing it right or is there a way to optimize things?