I have some code which uses some data from the database: Assignment and the Collection: todolist, which is supposed to interact with MongoDB and to add, delete or list the JSON in the collection.
To understand the problem I have to show the code before I explain it.
Here is the code for the model:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
id: {
type: String,
unique: true
},
desc: {
type: String
}
});
module.exports = mongoose.model('Task', TaskSchema);
Here is the code for the controller:
'use strict';
var mongoose = require('mongoose'),
Task = mongoose.model('Task');
exports.list_all_tasks = function(req, res) {
console.log("listing should commence");
Task.find({}, function(err, task) {
if (err)
res.send(err);
return;
res.json(task);
});
};
exports.create_a_task = function(req, res) {
var new_task = new Task(req.body);
new_task.save(function(err, task) {
if (err)
res.send(err);
return;
res.json(task);
});
};
exports.delete_a_task = function(req, res) {
Task.deleteOne({
_id: req.params.taskId
}, function(err, task) {
if (err)
res.send(err);
return;
res.json({n: task.n, ok: task.ok});
});
};
Here is the code for the route:
'use strict';
module.exports = function(app) {
var todoList = require('./controller');
// todoList Routes
app.route('/tasks')
.get(todoList.list_all_tasks)
.post(todoList.create_a_task);
app.route('/tasks/:taskId')
.delete(todoList.delete_a_task);
};
Server.js file:
const express = require('express');
const app = express();
const port = 3000;
var mongoose = require('mongoose');
Task = require('./api/model'); //created model loading here
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
const controller = require('./api/controller');
// mongoose instance connection url connection
//P.S The username and password have been taken off this security and privacy reasons
mongoose.connect('mongodb+srv://userName:password#server-4tjvi.mongodb.net/Assignment?retryWrites=true', { useNewUrlParser: true });
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('Welcome to Just Do It, your Node.js application for all your To Do List needs.');
console.log('todo list API server has started on: port ' + port);
Ok so the problem that I have is that when I type in localhost:3000/tasks into Postman, it says it is loading for a long time and then it says it could not get a response. What I want it to do is to list all the tasks (JSON) from the collection onto postman.
I have set up MongoDB, I have downloaded everything that is required as well; mongoose, nodemon, Mongodb, etc.
And how do I upload things from my node application to the database collection.
The problem in your code is with syntax. Consider the following code (out of the several)
Task.find({}, function(err, task) {
if (err)
res.send(err);
return;
res.json(task);
});
In this block of code your Task.find is going to return undefined and res.json is never reached. And since your server does not send any response, the request is just going to time-out.
Just because return is indented doesn't mean it's part of if block. To make it a part of if block you've to put it in braces {}
Here's an illustration:
function test() {
let out;
if (true)
out === 'yes';
return; // <-- not part of if block
console.log('never reached')
return out; // <-- never reached
}
console.log(test())
The above is equivalent to:
function test(x) {
let out;
if (true)
out === 'yes';
return; // return undefined
}
console.log(test())
So refactoring it:
Task.find({}, function(err, task) {
if (err) {
res.send(err);
return;
}
res.json(task);
});
Or return res.send
Task.find({}, function(err, task) {
if (err)
return res.send(err);
res.json(task);
});
Related
I have several mongodb collections,
Fruits: [ {}, {}, {} ...],
Bread: [{}, {}, {} ...]
I want to use dynamic collection name in my server like
// :collection will be "Fruits" or "Bread"
app.get('/fetch/:collection', function (req, res){
[req.params.collection].find({}, function(err, docs){
res.json(docs)
})
})
But as you know, [req.params.collection].find()... isn't working. How can I use dynamic collection name?
You can use the different collections using
db.collection('name').find({})
Here is the code i have tried
App.js
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require("mongodb").MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
var db;
MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to DB");
db = client.db('name of the db');
});
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/test/:collection', function(req,res){
let collection = req.params.collection;
console.log(collection);
db.collection(collection).find({}).toArray( function (err, result) {
res.send(result);
});
});
var port = 8000
app.listen(port, '0.0.0.0', () => {
console.log('Service running on port ' + port);
});
Hope this helps
This is not working as the collection name you are passing is just a variable with no DB cursor.
Here's what you can do here:
Create an index.js file, import all the models in that file with proper names as keys.
eg:
const model = {
order: require("./order"),
product: require("./product"),
token: require("./token"),
user: require("./user")
}
module.exports = model;
Let's assume your request URL is now.
/fetch/user
Now import this index.js as model in your controller file.
eg:
const model = require("./index");
Now you can pass the key as params in your request like and use like it is stated below:
app.get('/fetch/:collection', function (req, res){
model[req.params.collection].find({}, function(err, docs){
res.json(docs) // All user data.
})
})
Hope this solves your query!
I will give solution for this but I don't know is this as per developer standards
let your model names, fruit.js and bread.js in model folder
app.get('/fetch/:collection', function (req, res){
let collectionName = require(`./models/${req.params.collection}`)
collectionName.find({}, function(err, docs){
res.json(docs)
})
})
Hope this will work
I am creating a node and express REST application with a PostgreSQL database.
My question is how to define the connection variable globally in a minimalist express application (for a Hello World example)?
I have the following file structure with the following key files included.
{PROJECT_ROOT}\bin\www
{PROJECT_ROOT}\app.js
{PROJECT_ROOT}\routes\index.js
{PROJECT_ROOT}\db\db.js
{PROJECT_ROOT}\db\location.js
{PROJECT_ROOT}\OTHER FILES
The db.js should contain definition of a variable for a connection to the PostgreSQL database globally. This variable should be shared by other modules whenever necessay so that duplicated connections should be avoided.
db.js
var promise = require('bluebird');
/**
*Use dotenv to read .env vars into Node
*/
require('dotenv').config();
const options = {
// Initialization Options
promiseLib: promise,
connect(client, dc, useCount) {
const cp = client.connectionParameters;
console.log('Connected to database:', cp.database);
}
};
const pgp = require('pg-promise')(options);
const connectionString = process.env.PG_CONN_STR;
const db = pgp(connectionString);
module.exports = {
pgp, db
};
location.js defines the business logic to manipulate the gcur_point_location table.
var db_global = require('./db');
var db = db_global.db;
// add query functions
module.exports = {
getAllLocations: getAllLocations,
getLocation: getLocation,
createLocation: createLocation,
updateLocation: updateLocation,
removeLocation: removeLocation
};
function getAllLocations(req, res, next) {
db.any('select * from gcur_point_location')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL GCUR Point Locations'
});
})
.catch(function (err) {
return next(err);
});
}
function getLocation(req, res, next) {
var locationId = parseInt(req.params.id);
db.one('select * from gcur_point_location where locationid = $1', locationId)
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ONE Location by Id'
});
})
.catch(function (err) {
return next(err);
});
}
function createLocation(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into gcur_point_location(locationname, locationstatus, lng, lat)' +
'values(${locationname}, ${locationstatus}, ${lng}, ${lat})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one Location'
});
})
.catch(function (err) {
return next(err);
});
}
function updateLocation(req, res, next) {
db.none('update gcur_point_location set locationname=$1, locationstatus=$2, lng=$3, lat=$4 where locationid=$5',
[req.body.locationname, req.body.locationstatus, parseFloat(req.body.lng),
parseFloat(req.body.lat), parseInt(req.params.id)])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Updated Location'
});
})
.catch(function (err) {
return next(err);
});
}
function removeLocation(req, res, next) {
var locationId = parseInt(req.params.id);
db.result('delete from gcur_point_location where locationid=$1', locationId)
.then(function (result) {
/* jshint ignore:start */
res.status(200)
.json({
status: 'success',
message: `Removed ${result.rowCount} Location`
});
/* jshint ignore:end */
})
.catch(function (err) {
return next(err);
});
}
Likewise, munipulation of different tables will be defined in individual js files. All of them will require the db.js.
routes/index.js
var express = require('express');
var router = express.Router();
var db = require('../db/location');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/locations', db.getAllLocations);
router.get('/api/location/:id', db.getLocation);
router.post('/api/location', db.createLocation);
router.put('/api/location/:id', db.updateLocation);
router.delete('/api/location/:id', db.removeLocation);
module.exports = router;
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I would like to have some ideas about whether the above code is a good or a bad practise or any potential failure?
Most of the code makes sense to me, though I would implement your own ORM and model layers, so you can remove some of the code for PSQL queries and follow MVC design pattern. If all you are building is an express api server, then you do not need the View portion.
I usually have a file called ORM, which has something similar to the following:
var orm = {
all: function(tableInput, cb) {
var queryString = "SELECT * FROM " + tableInput + ";";
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
},
create: function(table, cols, vals, cb) {
var queryString = "INSERT INTO " + table;
queryString += " (";
queryString += cols.toString();
queryString += ") ";
queryString += "VALUES (";
queryString += printQuestionMarks(vals.length);
queryString += ") ";
console.log(queryString);
connection.query(queryString, vals, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
},
// An example of objColVals would be {name: panther, sleepy: true}
update: function(table, objColVals, condition, cb) {
var queryString = "UPDATE " + table;
queryString += " SET ";
queryString += objToSql(objColVals);
queryString += " WHERE ";
queryString += condition;
console.log(queryString);
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
}
};
// Export the orm object for the model (cat.js).
module.exports = orm;
Then I define a model file for each table you have in psql as following:
// Import the ORM to create functions that will interact with the database.
var orm = require("../config/orm.js");
var cat = {
all: function(cb) {
orm.all("cats", function(res) {
cb(res);
});
},
// The variables cols and vals are arrays.
create: function(cols, vals, cb) {
orm.create("cats", cols, vals, function(res) {
cb(res);
});
},
update: function(objColVals, condition, cb) {
orm.update("cats", objColVals, condition, function(res) {
cb(res);
});
}
};
// Export the database functions for the controller (catsController.js).
module.exports = cat;
A controller:
var express = require("express");
var router = express.Router();
// Import the model (cat.js) to use its database functions.
var cat = require("../models/cat.js");
// Create all our routes and set up logic within those routes where required.
router.get("/", function(req, res) {
cat.all(function(data) {
var hbsObject = {
cats: data
};
console.log(hbsObject);
res.render("index", hbsObject);
});
});
router.post("/api/cats", function(req, res) {
cat.create(["name", "sleepy"], [req.body.name, req.body.sleepy], function(result) {
// Send back the ID of the new quote
res.json({ id: result.insertId });
});
});
router.put("/api/cats/:id", function(req, res) {
var condition = "id = " + req.params.id;
console.log("condition", condition);
cat.update(
{
sleepy: req.body.sleepy
},
condition,
function(result) {
if (result.changedRows === 0) {
// If no rows were changed, then the ID must not exist, so 404
return res.status(404).end();
}
res.status(200).end();
}
);
});
// Export routes for server.js to use.
module.exports = router;
This follows MVC design pattern which is very easy to read and understand. So my whole folder structure would look something like this:
Best practices for structuring a database layer with pg-promise are shown in pg-promise-demo.
For a complete, real-world example of using that approach, see LISK database layer.
I'm trying to build a RESTful webservice following this tutorial:
https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
It's not working returning me a CANNOT GET/ reports error...
I'm trying to learn node.js and I can't find the error anywhere and everything I tried didn't work.
Also, when I call the server, it reaches to index.js which prints a "HEY". Wasn't this supposed to reach server.js first?
Here is my code:
Server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Report = require('./api/models/reportModel.js'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/server');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/reportRoute.js');
routes(app);
app.listen(port);
console.log('Report RESTful API server started on: ' + port);
reportRoute.js
'use strict';
module.exports = function(app) {
var reports = require('../controllers/reportController.js');
// report Routes
app.route('/reports')
.get(reports.list_all_reports)
.post(reports.create_a_report);
app.route('/reports/:reportId').get(reports.read_a_report)
.put(reports.update_a_report)
.delete(reports.delete_a_report);
};
reportController.js
'use strict';
var mongoose = require('mongoose'),
Report = mongoose.model('Reports');
exports.list_all_reports = function(req, res) {
Report.find({}, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.create_a_report = function(req, res) {
var new_report = new Report(req.body);
new_report.save(function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.read_a_report = function(req, res) {
Report.findById(req.params.reportId, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.update_a_report = function(req, report) {
Report.findOneAndUpdate({_id: req.params.taskId}, req.body, { new: true }, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.delete_a_report = function(req, res) {
Report.remove({
_id: req.params.reportId
}, function(err, report) {
if (err)
res.send(err);
res.json({ message: 'Report successfully deleted' });
});
};
Thank you for your help...
EDIT:
index.js
const express = require('express');
const app = express();
var route = require('./api/routes/reportRoute');
app.get('/', function(req, res) {
res.send('HEY!');
})
app.listen(3000, function(){console.log('Server running on port 3000')});
You haven't posted your reportController.js but this problem will occur if the function list_all_reports does not set a response body. For example, adding
res.json({hello: "world"});
to the handler function should make it work.
I am newbie in node.js and I'm sorry for my silly question.
I want to separate and organize my app for easy working with files. For this reason I create a module to do my mysql database there but I have problem with module.I can't return module data to use in my main js file app.js
console shows undefined and browser shows nothing
here is my code
App.js
var express = require('express'),
mysql = require('mysql'),
bodyParser = require('body-parser');
var app = express();
// app.set('view engine', 'jade');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: 'database'
});
var port = process.env.PORT || 8080;
var User = require('./models/userModels');
var bookRouter = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
bookRouter.route('/books')
.post(function (req, res) {
// console.log(book);
// res.send(book);
})
.get(function (req, res) {
res.send(User.allUsers); // <--- shows nothing
console.log(User.allUsers); //<--- returned undefined
});
app.use('/api', bookRouter);
app.get('/', function (req, res) {
res.send('welcome to my API');
});
app.listen(port, function () {
console.log('Running on PORT via gulp ' + port);
});
userModels.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "luxa"
});
module.exports = {
allUsers: con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
// console.log(result); // return result correctly
// return result;
callback(err, result); // Error
});
}),
};
what's my problem?
Okay I see a lot of wrong code here. Let's have a look on this part:
allUsers: con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
// console.log(result); // return result correctly
// return result;
callback(err , result); // Error
});
}) ...
First I can say that this is not a correct function declaration. And also I see that finally you are calling callback(err , result); but callback is coming from nowhere ... So the previous code could look like this:
allUsers: function (callback) {
con.connect(function (err1) {
if (err1){
/* use return to prevent the code to continue */
return callback(err1, null);
}
con.query("SELECT * FROM users", function (err2, result, fields) {
if (err2){
return callback(err2, null);
}
callback(err2, result);
});
});
}
Now lets have a look on this part of your code:
.get(function (req , res) {
res.send(User.allUsers); // <--- shows nothing
console.log(User.allUsers); //<--- returned undefined
})
Basically when doing User.allUsers you are doing nothing but passing the function itself. If you want to call function use (), so User.allUsers() is the right code, but this code is asynchronous and you will get nothing again ... Now comes the part to use the callback. So previous code can look like this:
.get(function (req, res) {
/* the code is async so first obtain the data then use res.send() */
User.allUsers(function (err, results) {
res.send({
error: err, /* here you should have any error if it happens */
results: results /* here you should have your results */
});
});
})
Check and see if the code is clear to you. Let me know if you have any questions.
I get `TypeError: Cannot set property 'auto' of null when i try to update my mongodb using angularjs on the frnt end and nodejs on the backend. Here is my code :
my angular code:
scope.lol.then(function(user){
console.log(user[0]._id);
iden=user[0]._id;
$scope.userss = user;
console.log(iden);
$http.put('/api/updateUser', user[0]);
});
And my api :
module.exports.updateUser = function (req, res) {
var id = req.param.id;
User.findById(id, function(err, user) {
if (err) throw err;
// change the users location
user.auto = 'true';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}
$http.put('/api/updateUser', user[0]);
change to
$http.put('/api/updateUser', {params:{id:user[0]._id}});
and on api
var id = req.param.id;
change to
var id = req.query.id;
I'm going to assume that you're using ExpressJS for your API, so you'll need to use body-parser to retrieve the body of your request. You can read more about it here: http://expressjs.com/en/api.html - ctrl+f for body-parser to skip to the good bits :)
Try something like this in your API (you'll probably need to tweak it to fit your app, but it shows you how to pull stuff out of the body of the request. There are code examples on the link I posted too):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.json());
app.use(express.urlencoded());
app.listen(1337);
app.put('/updateUser', updateUser);
function updateUser (req, res) {
var id = req.body.id;
User.findById(id, function(err, user) {
if (err) throw err;
// change the users location
user.auto = 'true';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}
Hope that helps!