Mongodb nodejs Check if exists - node.js

i'm trying to make an api which stores products and users!
at this time i want to make sure that the product which will be posted each has a unique Serial number and the code that will allow to have the same name, but i encouter the following error!
> TypeError: db.collection.find is not a function <br> at
> Object.module.exports.saveProductsignup
> (/home/themis/firstapp/api/config/database.js:14:19) <br>
> at /home/themis/firstapp/api/server.js:103:21 <br>
> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:312:12)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
server.js
var express = require('express'),
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl= 'mongodb://localhost:27017/firstapp';
var access = require('./config/database.js');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
//User authentication (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
//create posts about product (POST http://localhost:8080/api/createpost)
apiRoutes.post('/resources/createpost', function (req, res) {
if (!req.body.issue || !req.body.SN) res.status(400).send("Please give an issue and a S/N for the product");
else {
access.savePost(db, req.body.issue, req.body.SN, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Post Created");
});
}
});
apiRoutes.post('/resources/productsignup', function (req, res) {
if (!req.body.name || !req.body.serialnumber) res.status(400).send("Please give a name and a Serial number for the product");
else {
access.saveProductsignup(db, req.body.name, req.body.serialnumber, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Post Created");
});
}
});
//restricted log in (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
//demo Start
apiRoutes.delete('/resources/productinfo/:id', function(req, res, next) {
Products.findByIdAndRemove(req.params.id, req.body, function(err, post){
if (err) return next(err);
res.json(post);
});
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
access.findProductsByName(db, req.param('name'), function(info) {
if (!products) res.status(500).send("server error");
else res.status(200).send(info);
});
}
});
//demo End
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.savePost = function (db, issue, SN, callback) {
db.collection('posts').save({
issue: issue,
SN: SN
}, callback);
};
module.exports.saveProductsignup = function (db, name, serialnumber, callback) {
db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })
db.collection('products').save({
name: name,
serialnumber: serialnumber
}, callback);
};
module.exports.findProductsByName = function (model, name, callback) {
model.findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};

You have a typo in database.js in module.exports.saveProductsignup:
db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })
Should be:
db.collection('products').find({ "serialnumber" : { $exists : true, $ne : null } })

Related

'username: req.body.username' username in last of line is undefined

Hello I am creating login-register system in my project, actually I made it in many of my previous projects but this time I am getting an error, for which I've seen many posts related to this but none of them worked for me.
I got some issues on "verifySignUp.js" that
"TypeError: Cannot read property 'username' of undefined"
on last 'undefined' of line 'username: req.body.username'
and This is my postman data push
{
"username":"deayhrovv",
"email":"deayhrovv#gmail.com",
"password":"123456",
"roles":["user","moderater"]
}
this is my server.js
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
var dbConfig = require("./app/config/db.config");
var db = require("./app/models");
var Role = db.role;
var app = express();
// routes
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
var corsOptions = {
origin: "http://localhost:8080"
};
db.mongoose
.connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
}
});
}
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json())
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Canteen Food Order APIs application ."});
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on url ${corsOptions.origin}.`);
});
This is my middlewares
const { verifySignUp } = require("../middlewares");
const controller = require("../controllers/auth.controller");
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
};
This is my verifySignUp.js
const db = require("../models");
const ROLES = db.ROLES;
const User = db.user;
checkDuplicateUsernameOrEmail = (req, res, next) => {
User.findOne()
// Username
User.findOne({
username: req.body.username
}).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (user) {
res.status(400).send({ message: "Failed! Username is already in use!" });
return;
}
// Email
User.findOne({
email: req.body.email
}).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (user) {
res.status(400).send({ message: "Failed! Email is already in use!" });
return;
}
next();
});
});
};
checkRolesExisted = (req, res, next) => {
if (req.body.roles) {
for (let i = 0; i < req.body.roles.length; i++) {
if (!ROLES.includes(req.body.roles[i])) {
res.status(400).send({
message: `Failed! Role ${req.body.roles[i]} does not exist!`
});
return;
}
}
}
next();
};
const verifySignUp = {
checkDuplicateUsernameOrEmail,
checkRolesExisted
};
module.exports = verifySignUp;
Incase of GET request, you need to access the parameters using req.query instead of req.body. So, modify the simple route to following
app.get("/", (req, res) => {
Username = req.query.username
res.json({ message: "Welcome to Canteen Food Order APIs application ." + Username });
});

express-validator isDate and isISO8601 are always false

I'm trying to validate a date. I have tried everything I can but I have not found a solution. Input {"dob": "2002-10-02"}
'use strict'
var validator = require('validator');
var controller = {
create: (req,res) =>{
//pick parameters
var parameters = req.body;
//validator
try {
//not working (always returns false)
//var validate_dob = validator.isDate(parameters.dob + '');
//also not working (always returns false)
//var validate_dob = validator.isISO8601(parameters.dob + '');
} catch (error) {
return res.status(400).send({
message: error
});
}
}
}
In your question you mention tag express-validator, but in your middleware you use pure validator.
Here I am putting an example using the express-validator lib (version 6.6.0). To use validate body parameters (login and password). But you can get the idea and pick the validation for your date from the validators list. Reference.
server/validators/login.validator.js
const { body, validationResult } = require('express-validator');
exports.validationBodyRules = [
body('login', 'login is required').exists(),
body('password', 'password is required').exists(),
body('login', 'login is required').notEmpty(),
body('password', 'password is required').notEmpty()
];
exports.checkRules = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
Here is the routes file
server/routes/login.route.js
const router = require('express').Router();
const loginService = require('../controllers/login.controller');
const loginValidator = require('../validators/login.validator');
router.post('/login', loginValidator.validationBodyRules, loginValidator.checkRules, loginService.hashPassword, loginService.lookupLogin, loginService.logEmployee);
module.exports = router;
server/controllers/login.controller.js
const postgres = require('../../lib/postgres');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
exports.logEmployee = (req, res) => {
res.status(200).json({ token: 'Bearer ' + jwt.sign(req.employee, process.env.SECRET, { expiresIn: 1800 }) });//expires in 1800 seconds
res.end();
};
exports.hashPassword = (req, res, next) => {
crypto.scrypt(req.body.password.toString(), 'salt', 256, (err, derivedKey) => {
if (err) {
return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not do login', param: req.params.id }] });
}
req.body.kdfResult = derivedKey.toString('hex');
next();
});
};
exports.lookupLogin = (req, res, next) => {
const sql = 'SELECT e.employee_id, e.login FROM employee e WHERE e.login=$1 AND e.password = $2';
postgres.query(sql, [req.body.login, req.body.kdfResult], (err, result) => {
if (err) {
return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not do login', param: req.params.id }] });
}
if (result.rows.length === 0) {
return res.status(404).json({ errors: [{ location: req.path, msg: 'User or password does not match', param: req.params.id }] });
}
req.employee = result.rows[0];
next();
});
};
But you can use the ideas here to use a date validator.
If you need a more complete example, please, let me know.

CANNOT GET with mongodb and nodejs

hello i'm trying to GET a book by his name from my db but when i execute the script the localhost shuts down and i have to restart. also i get the error :
ReferenceError: text is not defined
here is the server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
//display a specific product stored in database
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
Products.find(Products, req.param('name'), function(Products) {
if (!text) res.status(500).send("server error");
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
and the database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection('text').save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection('text').findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
What am i doing wrong?
not sure if there are other issues with the code. but with the error ReferenceError: text is not defined, might the compiler be complaining that they cannot determine where text was declared in the following lines?
apiRoutes.get('/book/:title', function (req, res) {
...
if (!text) res.status(500).send("Server error");
...
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
...
if (!text) res.status(500).send("server error");
...
if that is the error, you might need to replace text with req.body.text

ReferenceError: db is not defined when i try to GET data from server

i develop a new project for my school and i try to fetch some data from my database but i ecounter that error in my terminal:
ReferenceError: db is not defined
here are my files from my project:
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
db.products.find();
if (err) return next(err);
res.json(post);
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
// Start the server
app.listen(port);
console.log('http://localhost:' + port);
and database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
package.json:
{
"name": "firstapp",
"main": "server.js",
"dependencies": {
"bcrypt": "^0.8.5",
"body-parser": "~1.9.2",
"express": "~4.9.8",
"jwt-simple": "^0.3.1",
"mongoose": "~4.2.4",
"mongodb" : "~1.2.5",
"morgan": "~1.5.0",
"passport": "^0.3.0",
"passport-jwt": "^1.2.1"
}
}
Because db is not defined and you don't need it just use the model "products", just change this
apiRoutes.get('/productinfo' , function(req, res, next) {
db.products.find();
if (err) return next(err);
res.json(post);
});
To this
apiRoutes.get('/productinfo' , function(req, res, next) {
products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});

TypeError: db.collection is not a function, CANNOT GET

i'm trying to get some data from the apiRoutes.get('/resources/productinfo/:name') and i have this error, i dont know whats going wrong... also the apiRoutes.get('/book/:title') doesnt seems to work! i dont know what am i doing wrong
UPDATED:
> TypeError: Cannot read property 'findOne' of undefined <br> at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26) <br>
> at /home/themis/firstapp/api/server.js:109:22 <br>
> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
> <br> at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
here is the server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!req.body.text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
access.findProductsByName(Products, req.param('name'), function(Products) {
if (!products) res.status(500).send("server error");
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
and the database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
and the package.json
{
"name": "firstapp",
"main": "server.js",
"dependencies": {
"bcrypt": "^0.8.5",
"body-parser": "~1.9.2",
"express": "~4.9.8",
"jwt-simple": "^0.3.1",
"mongoose": "~4.2.4",
"mongodb" : "~1.2.5",
"morgan": "~1.5.0",
"passport": "^0.3.0",
"passport-jwt": "^1.2.1",
"redis": "~0.10.1"
}
}
incorect syntax, you must read property of db.collection, but you call that. Example:
db.collection['products']!!!
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
For example
var object = {
'some_value': 'value',
'some_methid': function(){ return 'method result'}
}
You can read and set property 'some_value', for example:
object['some_value'] // return 'value'
object.some_value // return 'value'
// STEP 2
Ok, in your methods of database.js you pass db variable, but this is not of db instance, it is mongoose model, and you must write like this:
module.exports.findBookByTitle = function (model, title, callback) {
model.findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (model, name, callback) {
model.findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
You can only declare module.exports once in a file, so you should change:
In your database.js file:
module.exports.saveBook
to
exports.saveBook
and so on
Take a look at this: https://www.sitepoint.com/understanding-module-exports-exports-node-js/
in package.json folder find mongodb inside dependencies and update with these value:
"mongodb": "^2.2.33",
Then Run
npm install
again. That will solve your probem.
Make sure to add following to the scripts sectionin your package.json file
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js",
"debugger": "DEBUG=*:* npm run dev"
},

Resources