express callback not being called in separate module - javascript

When trying to call the results.js callback it will not execute. The showDate function will execute and write the console.log. When debugging it seems to exectute the routing functionality.
However when posting to the page from the search.ejs it will give a 404 for the route.
app.js
var express = require("express");
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
//MongoDB
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/time_report");
var userSchema = new mongoose.Schema({
name: String,
password: String
});
var user = mongoose.model("user", userSchema);
module.exports = {
app: express(),
user
};
var resultJS = require("./results.js");
resultJS.showDate();
results.js
var test = require("./app.js");
function showDate() {
console.log("showDate"); // Will execute on application startup
test.app.post("/results", function(req, res) {
res.render("results"); //Not executing
//Get login info
var uName = req.query.username;
var pw = req.query.password;
});
}
module.exports.showDate = showDate;

Related

Nodejs/express - Router.use() requires middleware function but got a ' + gettype(fn));

I'm new to back-end development with node and express. i'm trying to make a back-end for a simple blog with posts and user authentication to use later in an angular 4 app.
On the "Posts" end, after testing with chrome's addon "Postman", all seems to work fine but when i started working on the "Users" side it keeps throwing off the error:
"Router.use() requires middleware function but got a ' + gettype(fn));"
When i try to run the server. The code is below:
app.js
//Imports
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const config = require('./config/database');
//initialize App
var app = express();
//Setting port
var port = 3000;
//initialize cors
app.use(cors());
//Set static folder
app.use(express.static(path.join(__dirname,'../client/src')));
//initialize body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//Root route
app.get('/', function(req,res) {
res.send('Welcome to my API');
});
//Listen to port
app.listen(port, function () {
console.log('Server is running on post: ' + port);
});
//connection to DB
mongoose.connect(config.database);
mongoose.connection.on('connected', function () {
console.log('Connected to database' + config.database);
});
mongoose.connection.on('error', function (err) {
console.log('Database error' + err);
});
//Models
var Post = require('./models/post');
var User = require('./models/user');
//Routes
var postRouter = require('./routes/posts')(Post);
var userRouter = require('./routes/users')(User);
//Initialize routes
app.use('/api/posts', postRouter);
app.use('/api/users', userRouter);
models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userModel = new Schema({
name: {type: String},
email: {type: String, required:true},
username: {type: String, required:true},
password: {type: String, required:true}
});
module.exports = mongoose.model('Users',userModel);
routes/users.js
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
};
module.exports = userRoutes;
controllers/userController.js
var userController = function(User) {
var post = function(req,res) {
var bcrypt = require('bcryptjs');
//creating new instance of model and pass the bodyParser
var user = new User(req.body);
if(!req.body.username) {
res.status(400);
res.send('Name is required');
}
else if (!req.body.password) {
res.status(400);
res.send('Password is required');
}
else if (!req.body.email) {
res.status(400);
res.send('Email is required');
}
else {
bcrypt.hash(user.password, function (err, hash) {
user.password = hash;
});
//saving in db
user.save();
//status 201 means created
res.status(201);
//send result
res.send(user);
}
};
return {
post: post
};
};
module.exports = userController;
The problem occurs when i initialize the users route with
app.use('/api/users', userRouter);
in app.js
"Router.use() requires middleware function but got a ' + gettype(fn));"
the error comes from this line :
app.use('/api/users', userRouter);
app.use need a path and a middleware function. Here your returning
a simple function, not a middleware, that's why you got the error.
in routes/users.js you just have to return the express.Router middleware function.
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
// UserRouter is a middleware function
return UserRouter;
};
module.exports = userRoutes;
see express router part here : http://expressjs.com/en/guide/routing.html

how to save json object from third party api

I'm having trouble figuring out how to save a json object from a third party api to my personal localhost mongodb. I believe I'm supposed to create another method within the api controller but am not sure what kind of method should be used any help would be great thanks!
Here is my code sorry if this is a dumb question.
//server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var Router = require('./routes');
var morgan = require('morgan');
var port = process.env.PORT || 3000;
var app = express();
//database connect
mongoose.connect('mongodb://localhost/Emagispace')
app.use(
express.static('views'),
bodyParser.json(),
bodyParser.urlencoded({extended : true}),
morgan('dev')
);
Router(app);
app.listen(port, ()=>{
console.log(`Server running on ${port}`);
//Routes
var API = require('./controllers/api');
module.exports = (app)=>{
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './views'});
});
app.get('/api/emagispace', API.product)
}
//API controller
var request = require('request-promise');
var baseURI = 'example';
module.exports = {
product : (req, res)=>{
request({
method : 'GET',
url : `${baseURI}/api/emagispace/${req.query.products}`
})
.then((resp)=>{
console.log('Product list : ', resp);
res.send(resp).save();
})
}
}
In order use mongoose for saving the documents you'll need to specify the Schema first.
//product-model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: String,
price: String,
//And all other data you need
});
var Product = mongoose.model('Product', ProductSchema);
Also you can do validation and much else. Please see the docs.
Then you can use .insertMany to save them in one shot or iterrate over your documents:
var Product = require('../models/product-model.js');
...
.then((resp)=>{
//I assume that resp is an array of products here
console.log('Product list : ', resp);
//Go over your product list and save them
for (var product of resp) {
var p = new Product(product);
p.save();
}
//OR
Product.insertMany(resp);
res.send(resp);
})
After this you'll have products collection in your local db.
Also you can warp these calls into a method if you want.

How to create an database file in the mongoose and return back in the json format

Im reffering this video tutorial from this link "https://app.pluralsight.com/player?course=node-js-express-rest-web-services&author=jonathan-mills&name=node-js-express-rest-web-services-m6&clip=2&mode=live"....Here im returning the student in the json format...But dont know how to create it...So im getting an empty one...Is there any way to create that in the mongoose...Any1 please check my code and say
app.js
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/studentAPI');
var studentinfo = require('./models/studentModel');
var app = express();
var PORT = process.env.PORT || 3000;
var tutorRouter =express.Router();
tutorRouter.route('/student')
.get(function(req,res){
studentinfo.find(function(err,student){
if(err)
res.status(500).send(err);
else
res.json(student);
});
});
app.use('/api',tutorRouter)
app.get('/',function(req,res){
res.send('Welcome to my API')
});
app.listen(PORT,function(){
console.log('Running on port: ' + PORT);
});
studentModel.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema();
var studentModel = new mongoose.Schema({
name:{
type: String
},
parentname:{
type: String
}
});
module.exports = mongoose.model('studentinfo',studentModel);

Mongoose does not save anything to db with NodeJs

I have this very simple code that stores superhero name and power to database.
All connections work normally. When i ran mongod i used --dbpath C:/nodeprojects/sankarit/data. I have tried change the path like 50 times with different paths.
So my code sends nimi and supervoima (name, superpower) from client side and it tries to add them to database but literally nothing happens in db. When i write console.log("yay it works") on save function, it says that its working. And if i console log superhero it seems to work normally.
Here is client side:
$http.post("api/juttu", {nimi: "besthero", supervoima: "whiskey"}).success(function(response){
console.log(response.data);
}).error(function(){
console.log("Error")
})
Here is my server.js:
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.set('debug', true);
// SANKARI SCHEMA
var Sankari = require('./app/models/sankarit');
// CONTROLLERIT
var testCtrl = require('./server/testCtrl');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
// DB conn
// I have tried with /test, /heros, /sankariKanta, /sankarit
mongoose.connect('mongodb://127.0.0.1:27017/test');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
//PORTTI
var port = process.env.PORT || 8080;
// ROUTER
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.post("/api/juttu", testCtrl.juttu);
app.listen(port);
Here is the testCtrl:
var Sankari = require("../app/models/sankarit");
module.exports.juttu = function (req, res){
// Tried also var uusiSankari = new Sankari(req.body);
var uusiSankari = new Sankari();
uusiSankari.nimi = req.body.nimi;
uusiSankari.supervoima = req.body.supervoima;
uusiSankari.save(function(err){
if(err){
console.log(err);
} else{
// This is always showing up
console.log("This is working!");
}
});
};
Also when i try console.log(req.body); It is working correctly.
Here is schema(sankarit.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = ({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
When i run the program, the mongoose debug thing says:
Mongoose: sankaris.insert({ __v: 0, _id: ObjectId("57ff0a649dbf169c15000001"), nimi: 'besthero', s
upervoima: 'whiskey' }) {}
So when i debug and console log everything the program does it seems to work like dream. I have made these MEAN stack tutorials like 5-10 and everytime database worked normally. This is first time i'm trying to make whole code by myself. I tried solve this whole night but i didn't get absolutely anywhere.
You forgot to use the Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = Schema({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);

get data from mLab using modules

I trying to get data from mLab.
In function /getAll I am trying to get all the JSONs I entered in a collection.
I understood that to get all of the details I need to use the function find.
When I run it (node app.js) - I can see it waiting but nothing happens and I don't get anything on localhost:3000/getAll (it's not loading)
here is app.js
var express = require('express');
var app = express();
var stud = require('./grades');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://<myuser>:<mypass>#<dataaddress>');
var port = process.env.PORT || 3000;
mongoose.connection.once('open', function(){
stud(app);
mongoose.disconnect();
});
app.listen(port);
and this is gadres.js
var express = require('express');
var fs = require('fs');
var app = express();
var util = require('util');
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var studSchema = new schema({
id : {type:Number, unique:true, required:true},
name : {type:String, required:true},
grade : Number,
course : {type:String},
year : Number
},{collection: 'details'});
var stud = mongoose.model('stud', studSchema);
module.exports = function (app) {
app.get('/getAll', function(req, res) { // if url in path is getAll
stud.find({}, function(err, user){
if(err) throw err;
console.log(user);
});
})
});

Categories