get data from mLab using modules - javascript

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);
});
})
});

Related

express callback not being called in separate module

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;

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.

Schema hasn't been registred for model

i know the question already has been asking, but i can't figure out what i am doing wrong on my code, in my '/' when i start the app the router executes my index.js file that has the following code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Loja = require('../models/lojas');
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date());
console.log('Request Type:', req.method);
console.log('Request URL:', req.originalUrl);
next(); //passa a solicitação para a próxima função de middleware na pilha
});
//get all contacts with specific filter
router.post('/registo',function(req,res){
var loja = new Loja();
loja.name = req.body.name;
loja.email = req.body.email;
loja.setPassword(req.body.password);
loja.save(function(err){
var token;
token = loja.generateJwt;
res.status(200);
res.json({
"token": token
});
});
});
my app.js looks like following:
var express = require('express');
var bodyParser = require('body-Parser');
var mongoose = require('mongoose');
var passport = require('passport');
require('./config/passport');
var app = express();
var dbName = 'LojasDB';
var connectionString = 'mongodb://localhost:27017' + dbName;
mongoose.Promise = global.Promise;
mongoose.connect(connectionString);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-MethodOverride,Content-Type, Accept');
next();
});
app.use('/',require('./routes/index'));
app.listen(8080,function(){
console.log("listen on port 8080");
})
basicly i have a model called loja, that i want to use to authenticate, so i used passport for the first time to do this, but somehow i get a error that the schema hasn't been registred for that model, my model looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var lojasSchema = mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
lojasSchema.methods.generateJwt = function() {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000),
}, "12345"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
lojasSchema.methods.setPassword = function(password){
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};
lojasSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
return this.hash === hash;
};
module.exports = mongoose.model('Loja',lojasSchema);
so i am exporting the model here, so in my router index.js i require it like this:
var Loja = require('../models/lojas');
The following line:
var lojasSchema = mongoose.Schema({
should be:
var lojasSchema = new mongoose.Schema({
Make sure you are exporting your routes from that index.js file as I see they are separate from your app.js file. You need to require your Mongoose Models in your app.js file. So add something like this in your app.js.
var Loja = require('../models/lojas');

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);

Categories