Multiple app.post request but I get asertion error nodejs - node.js

post request a few but I can not make multiple post request or get request
When I write multiple app.post() or app.get I get error this error :
Assertion error :(function) is required How to fix this problem thnks all of you...
APPjs
var restify = require('restify');
var config = require('./config');
var app = restify.createServer({name:'REST-api'});
app.use(restify.fullResponse());
app.use(restify.bodyParser());
app.use(restify.queryParser());
app.listen(config.port, function() {
console.log('server listening on port number', config.port);
});
var routes = require('./routes')(app);
Route.JS
module.exports.my = function(app) {
var user = require('./controllers/userController');
var location=require('./controllers/locationController');
var ilan=require('./controllers/ilanController');
app.get('/', function(req, res, next) {
return res.send("WELCOME TO REST API");
});
//User get and create
app.post('/createUser', user.createUser); //Create Student API
app.get('/getUser',user.getUser);
//Ilan get and create
app.post('/createIlan',ilan.createilan);
app.get('/getIlan',ilan.getian);
//Location
app.get('/getlocation', location.getLocation);
};
DB.js
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.dbPath);
var db = mongoose.connection;
db.on('error', function () {
console.log('error occured from db');
});
db.once('open', function dbOpen() {
console.log('successfully opened the db');
});
exports.mongoose = mongoose;

Assertion error :(function) is required - this is head of error. You should to read trace bellow this error. Hope this helps.

Related

Creating MongoDB connection with mongoose

I am desperately trying to create a connection with mongoDB with the MEAN stack, using mongoose.
My MongoDB instance (mongod) is running and I can use mongo.exe and tested it by inserting some documents, it worked fine. But I have problems to create a connection to MongoDB with mongoose, and inserting a document with the .save() method does not work either...
I first wanted to try my POST method, created a function and tested it by creating some values in POSTMAN. But no documents were inserted in my MongoDB datbase..
This is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require("morgan");
//var routes = require('./routes');
//var cors = require('cors')
//configure app
app.use(morgan('dev')); //log requests to the console
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 5000;
//DATABASE SETUP
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DNZ'); //connect to uor datbaase
//Handle the connection event
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
//DNZ models live here
var FA = require('./models/DNZmodels/FA');
//ROUTES FOR OUR API
//=============================================================================
//create our router
var router = express.Router();
//middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
console.log('Today is:', Date())
next();
});
//test route to make sure everything is working (accessed at GET http://localhost:5000/DNZ/)
router.get('/', function(req, res) {
res.json({ message: 'Welcome to DNZ API!' });
});
//on routes that end in /FA
//----------------------------------------------------
router.route('/FA')
// create a FA (accessed at POST http://localhost:8080/DNZ/FA)
.post(function(req, res) {
//console.log(req.body);
//console.log(req.body.params);
//res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(req.body));
/*
var timestamp = req.body.Timestamp;
var prognostizierterBetriebswert = req.body.PrognostizierterBetriebswert;
var posFlexPot = req.body.posFlexPot;
var negFlexPot = req.body.negFlexPot;
var leistungsuntergrenze = req.body.Leistungsuntergrenze;
var leistungsobergrenze = req.body.Leistungsobergrenze;
var posGesEnergie = req.body.posGesEnergie;
var negGesEnergie = req.body.negGesEnergie;
var preissignal = req.body.Preissignal;
var dummy1 = req.body.Dummy1;
var dummy2 = req.body.Dummy2;
var dummy3 = req.body.Dummy3;
*/
var fa = new FA();
fa.name = req.body.name;
console.log("Hier erscheint var fa:", fa);
//console.log(Dummy1);
//res.send(JSON.stringify(timestamp));
// create a new instance of the FA model
/*
var fa = new FA({
Timestamp: timestamp,
Leistungsuntergrenze: leistungsuntergrenze,
Leistungsobergrenze:leistungsobergrenze,
PrognostizierterBetriebswert :prognostizierterBetriebswert,
posFlexPot: posFlexPot,
negFlexPot:negFlexPot,
posGesEnergie: posGesEnergie,
negGesEnergie: negGesEnergie,
Preissignal:preissignal,
Dummy1: dummy1,
Dummy2: dummy2,
Dummy3: dummy3
})
*/
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("debug");
res.status(200);
res.json({ message: 'FA created!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FA.find(function(err, fas) {
if (err)
res.send(err);
res.json(fas);
});
});
//on routes that end in /FA/:FA_id
//----------------------------------------------------
router.route('/FA/:FA_id')
// get the bear with that id
.get(function(req, res) {
FA.findById(req.params.bear_id, function(err, fa) {
if (err)
res.send(err);
res.json(fa);
});
})
// update the bear with this id
.put(function(req, res) {
FA.findById(req.params.FA_id, function(err, fa) {
if (err)
res.send(fa);
//bear.name = req.body.name;
/*
FA.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'FA updated!' });
});
*/
});
})
/*
// delete the bear with this id
.delete(function(req, res) {
FA.remove({
_id: req.params.bear_id
}, function(err, FA) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
*/
//REGISTER OUR ROUTES -------------------------------
app.use('/DNZ', router);
//START THE SERVER
//=============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
/*
// set static directories
app.use(express.static('./dist'));
app.use(cors());
// Define Routes
var index = require('./routes/index');
var users = require('./routes/users');
//Set up routes
routes.init(app)
//run
app.listen(port);*/
console.log('Server started, Listening on port ', port);
I used the "template" from the Bear tutorial:
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
the problem here is already, that there is no message: "DB connection alive". However, in the bear tutorial (whose code I used here), the DB connection is built and I can insert bear documents in the database. However, here it does not work...
and this is my FA Schema model from FA.js:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var FASchema = new Schema({
Timestamp: Date,
PrognostizierterBetriebswert: Number,
posFlexPot: Number,
negFlexPot: Number,
Leistungsuntergrenze: Number,
Leistungsobergrenze: Number,
posGesEnergie: Number,
negGesEnergie: Number,
Preissignal: Number,
Dummy1: Schema.Types.Mixed,
Dummy2: Schema.Types.Mixed,
Dummy3: Schema.Types.Mixed
//same: Dummy: {}
});
//var FASchema = new Schema({name: String});
module.exports = mongoose.model("FA", FASchema, 'FA');
console.log("FA wird ausgeführt!");
Anybody got an idea why there is no DB connection created?
when I test your code , the Error (Can't set headers after they are sent) was thrown. you can delete res.send(JSON.stringify(req.body)); and restart service

Node js & mongoDB - TypeError: db.collection is not a function

I am trying to post data from POSTMAN to an external database that I created on mLab but I am getting the error db.collection is not a function.
There is a similar question thread but the answer is incomplete and doesn't save any keys/values I put into postman to mLab. The code that I am trying to make work is from this tutorial: https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
My Code:
Server.js
const express = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api#ds123312.mlab.com:23312/soundfactory';
app.listen(port, () => {
console.log('')
console.log('We are live on ' + port);
console.log('')
});
MongoClient.connect(databaseURL, function(err, db) {
assert.equal(null, err);
console.log("API has succesfully connected to Sound Facotry mlab external database.");
console.log('')
db.close();
});
app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser
db.js
module.exports = {
url : 'mongodb://external:api#ds123312.mlab.com:23312/soundfactory'
};
index.js
const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};
note_routes.js
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
partially correct code
server.js (code that partially works & doesn't throw the db.collections error like my original server.js file )
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
//require('./app/routes')(app,{});
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})
Remove the node_modules folder and change mongodb version of your package.json
"mongodb": "^2.2.33"
and run below code :
npm install
change to this require('mongodb').MongoClient;

Node.JS Insert data to mongodb Web API , bodyParser issue

I need an API to android to insert data to mongodb , I'm following this , but
var song = req.body; TypeError: Cannot read property 'body' of undefined
I google few answer , which was need to install bodyParser , so I follow this to install bodyParser , but still get
var song = req.body; TypeError: Cannot read property 'body' of undefined
I'm not sure where I do wrong , please help
app code
var express = require('express'),
songs = require('./routes/route');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
// create user in req.body
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
route cote
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXXXX:XXXXXXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
You're not using jsonParser in your GET /songs route, only your POST /songs route. However, GET requests typically do not have request bodies. Values are typically passed in the url as query parameters in those cases, so you will probably want to instead look in req.query.

Mongodb Insert data API no respone

I need an API to insert data from android to mongodb , I follow this ,the code can run , have NO error , and I use POSTMAN try to post some data , it always say could not get any respone , seem to have an error connecting to 192.168.1.105:3000/songs
but I can use find all api and findByID.
This took me hours , please help , so depress :(
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:XXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
Okay so I changed a few things in your code. I'm successfully getting the request body in the app.js file. Do have a look at the code.
route.js
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://localhost:27017/test";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
Notice that I have changed the URI to localhost, so change it again to the one you specified.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
Since your only problem was that you weren't able to get the request body. You'll be able to get it with this code.
Also since your app.get('/songs',songs.addSong); is of type GET, you'll not be able to send POST Data through it. So change it to
app.post('/songs',songs.addSong);
Hope this helps.

Can not get data from MongoDB in Node.js

I try to build some Web Api to get data from MongodbLab ,I can call the api and reply string now , but can't not get data from mongodb , I follow many tutorial try for three hours , but the web and curl always reply [ empty reply from server ] , I believe is this part have some issue exports.findAll = function(req, res) {...}, please help
code
var express = require('express'),
songs = require('./routes/route');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://1111:aaaa#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};

Resources