I come to you because I have a problem that I can not solve.
I use nodejs, express and mongodb especially mongoose.
My express server works, but i can't insert documents into my database and i don't know why. With "console.log()" i saw that mongoose.model.save is never called or there is a probleme with this function.
My app.js
var express = require('express');
var bodyParser = require('body-parser');
var connect = require('connect');
var app = express();
var port = process.env.PORT || 8080;
// Configuration
app.use(connect.logger('dev'));
app.use(connect.json());
app.use(connect.urlencoded());
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.listen(port);
require('./routes/routes.js')(app);
console.log('The App runs on port ' + port);
My route.js
var writeData = require('/config/writeData');
var baseurl = '/niceproject'
module.exports = function(app) {
app.get(baseurl + '/', function(req, res) {
res.end("Node-Android-Project");
});
app.post(baseurl + '/writeTemp', function(req, res) {
var heure = req.body.heure;
var temperature = req.body.temperature;
console.log('req.body' + req.body);
writeData.writeTemperature(heure,temperature,function(found){
console.log(found);
res.json(found);
});
});
}
My writeData.js
var mongoose = require('mongoose');
var model = require('/config/models.js');
var temperatureCollection = model.temperature;
var personneCollection = model.personne ;
var sonCollection = model.sound;
exports.writeTemperature = function(heure,temperature,callback) {
var newTemperature = new temperatureCollection({
id : 1,
heure: new Date(),
temperature : temperature
});
console.log('new temp: ' + newTemperature);
newTemperature.save(function(err){
console.log('test');
if(err){
console.log('erreur' + err);
callback(err);
}
console.log(newTemperature);
callback({'response':"temperature ajouté"});
});
}
and my model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var temperatureSchema = mongoose.Schema({
id : Number,
temperature : Number,
heure : Date
});
var personneSchema = mongoose.Schema({
id : Number,
nbPersonne : Number,
heure : Date
});
var sonSchema = mongoose.Schema({
id : Number,
niveauDb : Number,
heure : Date
});
mongoose.connect('mongodb://localhost/nightAdvisorDatabase');
var temperatureModel = mongoose.model('temperature', temperatureSchema);
var personneModel = mongoose.model('personne', personneSchema);
var soundModel = mongoose.model('niveauDb',sonSchema);
module.exports = {
temperature : temperatureModel,
personne : personneModel,
sound : soundModel
};
So, when i made a post request with /niceproject/writeTemp path, i can see the newTemperatureobject in my writeData with the current date and the temperature send by the request, but i have problems with the newTemperature.save, nothings happens
Thanks for reading me
Hope than you could help me and sorry for my approximate english
If i read you right, the save method is not working on your model.
when you call the .save(), you should pass two parameters to the callback on the save method .
Instead of this one below.
newTemperature.save(function(err){
console.log('test');
if(err){
console.log('erreur' + err);
callback(err);
}
console.log(newTemperature);
callback({'response':"temperature ajouté"});
});
you should write it like this.
newTemperature.save(function(err,newTemp){
console.log('test');
if(err){
console.log('erreur' + err);
callback(err);
return;
}
console.log(newTemp);
callback({'response':"temperature ajouté"});
});
The newTemp parameter is used to hold the result,should the operation be successful.
Try out this solution. and give feedback.
It appears your are not using Promises or async/await to handle the asynchronous operations. please do look into anyone of them (especially async/await) available in node >= v7.7. It will make working with async operations a pleasure, shorter code with no callback hell.
Cheers.
Related
I'm on the Node.js repl, I created a new project folder and initialized the NPM, then I installed the Express package and wrote the following code into the js file:
const express = require('express');
const app = express();
app.listen(5000, function(){
console.log("server started on port 5000");
})
app.get("/", function(req, res){
res.send("Hi There! Welcome!")
})
app.get("/speak/:animalName", function(req,res){
var animalName = req.params.animalName;
var verso = "verso";
if (animalName = "pig"){
verso = "oink"
} else if (animalName = "dog"){
verso = "bau"
} else if (animalName = "cat"){
verso = "Miao"
}
console.log(req.params);
res.send("THE " + animalName + " says " + verso);
})
app.get("*", function (req, res){
res.send("Sorry, the page cannot be found")
})
When I open the js file with Nodemon the server starts correctly and when I type a specific pattern in the URL field the console.log returns me the req.params correctly (in the example below: for I typed "cat" the console returned { animalName: 'cat' }
Nonetheless, the response in the browser is not the correct one:
You're using a single = in your conditions. This always assigns the variable, instead of testing for equality. Use == or ===.
this is my first time asking questions and this is basically my last resort in finding some answers. Im a noob and beginner in javascript so please use simple terms with me.
So i have an issue. I dont know how to query.
- As in do i put all my queries in one script or do i have to split them up to different scripts.
- Right now, i have a server.js and i put all my codes in there. including queries. So how do i run just one of them.
- and also if there is such a thing for me to query for just another number like 4. Do i have to go back to the script to manually change from '110' to '4' or can i just enter it somewhere.
Some examples are:
//length of 110
db.collection.find({length: "110"}, function(err, collection) {
if( err || !collection) console.log("No collections with 110 in length");
else collection.forEach( function(length) {
console.log(length);
} );
});
//shows record of length 110 and length 340
var length = ['110', '340']
length = length.join('|');
var re = new RegExp(length, 'i')
db.collection.find({length:{$regex: re}}, function(err, collection) {
if( err || !collection ) console.log("User not found");
else collection.forEach (function(length){
console.log(length);
});
});
How do i query to only run for one of them in mongodb. Appericiate the help alot guys
You already know that node.js is used for making servers. So there are 2 ways you can query the database. Since you're new to node, I'm going to list both the ways :
1.A http GET for querying data (Standard Way)
You can write a simple http server and set a route for getting the type of data you want.I've written a small file so that you can understand:
var express = require('express');
var http = require('http');
var app = express();
var bodyParser = require('body-parser');
// Db settings
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function getConnection(url, callback) {
MongoClient.connect(url, function(dbErr, dbRes) {
if(dbErr) {
return callback(err, null);
}
callback(null, dbRes);
});
}
// Configure app to use bodyparser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 7013;
app.set('port', port);
app.use(function(req, res, next) {
console.log(req.ip+ ":"+port + req.url + " "+req.method);
next();
});
app.get('/getCityData', function(req, res, next) {
var cityName = req.query.city;
getConnection(url, function(conErr, db) {
if(conErr) {
return res.send("ERROR IN GETTING connection");
}
var cityCollection = db.collection('cities');
cityCollection.find({"city":cityName}).toArray(function(err, result) {
if(err) return res.send("error in querying data");
db.close();
res.send(result);
});
});
});
var httpServer = http.createServer(app).listen(port, function() {
console.log("Express server listening on port "+app.get('port'));
});
You can query the server using curl or postman like this :
2.Using command line arguments :
You can also do it the easy way using command line arguments by passing the parameter to query, but it's less flexible:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function getConnection(url, callback) {
MongoClient.connect(url, function(dbErr, dbRes) {
if(dbErr) {
return callback(err, null);
}
callback(null, dbRes);
});
}
var cityName = process.argv[2]; // that's the argument you'd receive
getConnection(url, function(conErr, db) {
if(conErr) {
return res.send("ERROR IN GETTING connection");
}
var cityCollection = db.collection('cities');
cityCollection.find({"city":cityName}).toArray(function(err, result) {
if(err) return res.send("error in querying data");
db.close();
console.log(result);
});
});
Pass that commandline argument like this while executing file :
I hope it helps
The code is only displaying the last record from the database. What do I do to get it to display all the records from the database. I'm trying this by using nodeJS. Thank you
var express = require('express');
var mysql = require('mysql');
var app = express();
var data;
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'music'
});
connection.connect();
connection.query('SELECT * FROM artist', function(err, rows, fields) {
if(err) throw err;
data = JSON.stringify(rows);
for(var i=0;i<rows.length;i++)
data = rows[i].artist_name + " "+rows[i].artist_id;
});
connection.end();
app.get("/artists", function(req,res){
res.send(data);
})
var myServer = app.listen(3000, function(){
console.log("Server listening on port 3000");
})
You are assigning your data value to each row in the for loop; that is, every iteration of the loop, you replace the value. Instead of using the assignment operator (=) use a contaminator (+=):
var data = "";
var rowDelimiter = "<br>"; // Or whatever you want
And then:
data += rows[i].artist_name + " "+rows[i].artist_id + rowDelimiter;
I'm very new to node.js and I'm having struggle with querying to MySQL DB. This is a very simple web page, all I have to do is read the value from the input and search it on my DB.
The problem is that var num is still undefined when the web page executes the query. How do I guarantee that I get that value before executing the query?
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var express = require('express');
var mysql = require('mysql');
var port = process.env.PORT || 8001;
var router = express.Router();
var app = express();
var server = http.createServer(app);
var n_eleitor;
var nome;
var local;
var num_bi;
var num;
// ---- ROUTES ------
app.get('/', function(req, res) { //homepage
res.sendFile(__dirname+'/index.html');
handle_database(req, res);
});
app.get('/result', function(req, res, next) { //results
res.render('result.ejs', { n_eleitor: n_eleitor, local: local, nome: nome });
});
app.use('/', router);
// ---- CONECTION -----
server.listen(port);
var listener = io.listen(server);
listener.sockets.on('connection', function(socket){
socket.on('client_data', function(data){ //receive data from client
//console.log(data.letter);
num_bi = data.letter;
console.log(num_bi);
var num = "'"+num_bi+"'";
console.log(num);
});
});
// ---- MYSQL ------
var pool = mysql.createPool ({ //pool maitains a cache of database connections -> handles multiple connections
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : 'soraia',
database : 'pti2',
});
function handle_database(req, res) {
pool.getConnection(function(err, connection){
if(err){
connection.release(); //connection returns to the pool, ready to be used again by someone else.
return;
}
//console.log('ID:' + connection.threadId);
connection.query("select eleitor.*, freguesia.designacao from freguesia, eleitor where num_bi= ? and freguesia.cod_freg=eleitor.cod_freg",[num], function(err, rows, fields){
n_eleitor = rows[0].cod_eleitor;
nome = rows[0].nome;
local = rows[0].designacao;
connection.release();
console.log(num);
console.log(rows);
});
});
}
When I run the program I get "TypeError: Cannot read property 'cod_eleitor' of undefined" and I think that's because what I said before...
Can someone help me, please?
If you had a server js like so:
var app = require('express'),
http = require('http'),
news = require('./server/api/news'),
db = require('mongoose');
/* app config..... */
app.get('/api/news', news.list);
var server = http.createServer(app);
server.listen(app.get('port'), function () {
console.log("Server running");
});
And I wanted to create an API to handle adding news items to the database:
var db = require('mongoose');
/*** Public Interfaces ***/
function list(req, res) {
var offset = ~~req.query.offset || 0,
limit = ~~req.query.limit || 25;
db.News.find(function (err, newsItems) {
res.json(newsItems.slice(offset*limit, offset*limit + limit));
});
}
exports.list = list;
This API would exist in its own file, how do I use the instance of the db created in the server.js inside the new module.
Or do you create and open a new connection each time you query the database?
Thanks
I would probably do it more like this
the server :
var express = require('express'),
app = express(),
http = require('http'),
db = require('mongoose'),
news = require('./server/api/news')(db); // you can pass anything as args
app.get('/api/news', news.list);
/* add routes here, or use a file for the routes */
// app.get('/api/morenews', news.more_news); .... etc
http.createServer(app).listen(8000);
and in the ../news/index.js file or whatever you're using, I'd use a literal, but you can always use exports to pass back each method as well
module.exports = function(db) {
/* now db is always accessible within this scope */
return {
list : function (req, res) {
var offset = ~~req.query.offset || 0,
limit = ~~req.query.limit || 25;
db.News.find(function (err, newsItems) {
res.json(newsItems.slice(offset*limit, offset*limit + limit));
});
}, // now you can easily add more properties
more_news : function(req, res) {
res.end('Hello kitty');
}
}
}