I'm implementing a little server application with node.js and ran in a problem, where the collection.find() method is not recognized.
Here is my code:
// THIS FUNCTION WORKS CORRECTLY
var find_all_seasons = function (callback) {
var season_collection = db.get().collection('season_collection');
// Find some documents
season_collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
};
// HERE I ALWAYS GET THE EXCEPTION
var find_speaker_by_name = function (name, callback) {
var speaker_collection = db.get().collection('speaker_collection').find({"name":name})(function(err, doc) {
assert.equal(err, null);
console.log("Found the following records");
console.log(doc.name)
callback(doc);
});
};
........
app.get('/api/speakers/:name', function (req, res) {
var name = req.params.name;
find_speaker_by_name(name, function (err, result) {
if (err)
res.send(err);
res.json(result);
})
});
Exception:
TypeError: db.get(...).collection(...).find(...) is not a function
at find_speaker_by_name
My DB Connection:
var MongoClient = require('mongodb').MongoClient
var state = {
db: null
};
exports.connect = function(url, done) {
if (state.db) return done();
MongoClient.connect(url, function(err, db) {
if (err) return done(err);
state.db = db;
done()
})
};
exports.get = function() {
return state.db
};
exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null
state.mode = null
done(err)
})
}
};
Related
I am a node.js and MySQL beginner and I just started setting up and trying out some basic code.
I find these two APIs to practice, one is the API for the CRUD database, and the other is the API for judging user login / registration.I tried to merge the APIs of these two files, and the result was a problem. I think the current problem is the configuration file (conf.js).I plan to write a function and then wrap any file and use it again, so that the configuration files may not conflict, but I don’t know how to start.
These are the two API teaching URLs I practiced
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
https://www.footmark.info/programming-language/nodejs/nodejs-restful-webapi-mysql/
index.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var authenticateController = require("./controllers/authenticate-controller");
var registerController = require("./controllers/register-controller");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/api/register", registerController.register);
app.post("/api/authenticate", authenticateController.authenticate);
app.listen(3000);
app.js
var bodyparser = require("body-parser");
var express = require("express");
var conf = require("./conf");
var functions = require("./functions");
var user = require("./routes/user");
var app = express();
req.body
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.use(functions.passwdCrypto);
app.use("/user", user);
app.listen(conf.port, function() {
console.log("app listening on port " + conf.port + "!");
});
authenticate-controller.js
var connection = require('./../conf');
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
if(password==results[0].password){
res.json({
status:true,
message:'successfully authenticated'
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
register-controller.js
var connection = require('../conf');
module.exports.register=function(req,res){
var today = new Date();
var user={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
});
}
user.js(models)
var mysql = require("mysql");
var conf = require("../conf");
var connection = mysql.createConnection(conf.db);
var sql = "";
module.exports = {
items: function(req, callback) {
sql = "SELECT * FROM user";
return connection.query(sql, callback);
},
item: function(req, callback) {
sql = mysql.format("SELECT * FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
add: function(req, callback) {
sql = mysql.format("INSERT INTO user SET ?", req.body);
return connection.query(sql, callback);
},
delete: function(req, callback) {
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
put: function(req, callback) {
connection.beginTransaction(function(err) {
if (err) throw err;
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
connection.query(sql, function(err, results, fields) {
if (results.affectedRows) {
req.body.id = req.params.id;
sql = mysql.format("INSERT INTO user SET ?", req.body);
connection.query(sql, function(err, results, fields) {
if (err) {
connection.rollback(function() {
callback(err, 400);
});
} else {
connection.commit(function(err) {
if (err) callback(err, 400);
callback(err, 200);
});
}
});
} else {
callback(err, 410);
}
});
});
},
patch: function(req, callback) {
sql = mysql.format("UPDATE user SET ? WHERE userId = ?", [req.body, req.params.id]);
return connection.query(sql, callback);
}
};
user.js(routes)
var express = require("express");
var user = require("../models/user");
var router = express.Router();
router
.route("/")
.get(function(req, res) {
user.items(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.post(function(req, res) {
user.add(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
res.status(201).json(results.insertId);
});
});
router
.route("/:id")
.get(function(req, res) {
user.item(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.delete(function(req, res) {
user.delete(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
res.sendStatus(204);
});
})
.put(function(req, res) {
user.put(req, function(err, results) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (results === 410) {
res.sendStatus(410);
return;
}
user.item(req, function(err, results, fields) {
res.json(results);
});
});
})
.patch(function(req, res) {
user.patch(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
req.body.id = req.params.id;
res.json([req.body]);
});
});
module.exports = router;
conf.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "farmbot",
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
/*If I comment out the code below, I can execute the login / register API*/
/*Without commenting out, can only perform CRUD on the database*/
module.exports = {
db: {
host: "localhost",
user: "root",
password: "1234",
database: "farmbot"
},
port: 3000
};
You will have to refactor them properly. You will need only once file to begin with. Why using it twice?
Refactor them in one file instead of listening to them on different ports. Once done, you can show the code to us so that we can fix it further if there's an issue.
Start from index.js and merge app.js with it but a bit carefully. I think doing it by yourself you will learn much from it.
db.js
pool.connect(function (err, client, done) {
client.query('SELECT id, user_id, name FROM public.chat;', function (err,
result) {
if (err) console.log("error" + err.message);
else {
module.exports.res = result.rows[0];
}
});
});
file app.js
var con = require('./db/connect');
console.log(con.res);
I'm getting the result undefined
,I don't understand, the reason is callback?
Try this:
db.js:
module.exports = pool.connect(function (err, client, done) {
client.query('SELECT id, user_id, name FROM public.chat;', function (err, result) {
if (err)
console.log("error" + err.message);
else
return result.rows[0];
});
});
app.js:
var con = require('./db/connect');
console.log(con());
I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});
The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).
var express = require('express');
var search = express.Router();
search.get('/', function(req, res, next) {
console.log('1');
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
console.log('last');
next();
});
var dbCall = function(callback) {
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');
var bucket = cluster.openBucket('default');
var doc;
var ViewQuery = couchbase.ViewQuery;
var query = ViewQuery.from('dev_test', 'allData');
bucket.query(query, function(err, viewResults) {
if (err) {
callback(err, null);
} else {
console.log('inqueryCall');
var results = viewResults;
callback(null, results);
console.log(results);
}
});
};
module.exports = search;
Here's the error that I get is :
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
Can someone please explain the issue here(not just the solution)?
I've added console.log and the issue here is that the couchbase call to async
Remove next() call, that is causing this error. next() is used in middleware to pass the flow to next middleware or endpoint/route
search.get('/', function(req, res, next) {
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
});
Hello i know that this question is common in stackoverflow but i passed by all of them and i really cannot get what is wrong with my code.
This is my main server.js
var dbUri = process.env.MONGODB_URI;
var app = express();
var PORT = process.env.PORT || 3001;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
if (app.settings.env === 'development') {
dbUri = 'mongodb://localhost/barsDb';
}
mongoose.connect(dbUri, function (err, res) {
if (err) {
console.log('Erorr connection to database ' + dbUri + '.' + err);
} else {
console.log('Connected to database on ' + dbUri + "\n");
}
});
//app.use(require('./routes.bars'));
require('./routes.bars')(app); //error here reciving undefined
// connect to server
app.listen(PORT, function () {
console.log('Listening to port ' + PORT + '...');
});
These are my routes.js
var bars = require('./controllers/controller.bar');
var mongoose = require('mongoose');
module.exports = function(app) {
app.route('/').get(bars.getMain); //error in this line it is returning undefinded.
app.route('/bars').get(bars.getBars);
app.route('/bars').post(bars.addBar);
app.route('/bars/:id').put(bars.updateBarById);
app.route('/bars/:loc').get(bars.getByLocation);
app.route('/bars/:id').get(bars.getBarById);
app.route('/bars/:id').delete(bars.deletBarById);
};
This is my controller:
var mongoose = require('mongoose');
var dbModel = require('./../model/bars.db');
var path = require('path');
var _ = require('underscore');
// main page
module.getMain = function (req, res) {
res.sendFile(path.join(__dirname + "/../public/index.html"));
};
// post new bar
module.addBar = function (req, res) {
var body = _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
console.log(body);
var newBar = new dbModel(body);
newBar.save(function (err) {
if (err) throw err;
//res.send('Bar Created');
res.status(201).send();
});
};
// get all bars
module.getBars = function (req, res) {
dbModel.find({},function (err, bars) {
if (err) throw err;
res.json(bars);
//res.status(200).send();
});
};
//get bars by location
module.getByLocation = function (req, res) {
var barLoc = req.params.loc.split(",");
var barLocLon = parseFloat(barLoc[0]);//.toFixed(5);
var barLocLat = parseFloat(barLoc[1]);//.toFixed(5);
barLoc = []; barLoc.push(barLocLon); barLoc.push(barLocLat);
dbModel.find({
loc: {$gt:[barLocLon - 0.0200, barLocLat - 0.0200], $lt:[barLocLon + 0.0200, barLocLat + 0.0200]}
}, function (err, bars) {
if (err) throw err;
res.json(bars);
res.status(200).send();
});
};
// get bar by id:
module.getBarbyId = function (req, res) {
var barId = req.params.id;
dbModel.findById(barId, function (err, bar) {
if (err) throw err;
res.json(bar);
res.status(200).send();
});
};
// update bar by id:
module.updateBarById = function (req, res) {
var barId = req.params.id;
var body = _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
dbModel.findById(barId, function (err, bar) {
if (bar) {
bar.save(function (err) {
if (err) throw err;
});
}
});
dbModel.findByIdAndUpdate(barId, {$set:req.body}, function (err, bar) {
if (err) throw err;
res.send('Updated');
});
};
// delete bar by id:
module.deleteBarById = function (req, res) {
var barId = req.params.id;
//console.log(barId);
dbModel.findByIdAndRemove(barId, function (err) {
if (err) throw err;
res.send('Deleted id ' + barId);
});
};
Wrap your functions like this.
var myFunctions = {
// get bar by id:
getBarbyId: function (req, res) {
var barId = req.params.id;
dbModel.findById(barId, function (err, bar) {
if (err) throw err;
res.json(bar);
res.status(200).send();
});
},
// update bar by id:
updateBarById: function (req, res) {
var barId = req.params.id;
var body = _.pick(req.body, 'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
dbModel.findById(barId, function (err, bar) {
if (bar) {
bar.save(function (err) {
if (err) throw err;
});
}
});
dbModel.findByIdAndUpdate(barId, {
$set: req.body
}, function (err, bar) {
if (err) throw err;
res.send('Updated');
});
},
// delete bar by id:
deleteBarById: function (req, res) {
var barId = req.params.id;
//console.log(barId);
dbModel.findByIdAndRemove(barId, function (err) {
if (err) throw err;
res.send('Deleted id ' + barId);
});
}
}
module.exports = myFunctions;
Now you can you use your "controller" like this:
var myControllerFuncs = require('path/controller.js');
//myControllerFuncs.updateBarById...