I'm new in javascript and I want to use webix.
I saw the get started and it's Ok...
So, my problem is that I can't display data from mongodb.
This is my server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
//connect to the mongo
var db = require('mongoskin').db("mongodb://localhost:27017/test", { w: 0});
db.bind('sites');
//create the app instance
var app = express();
//serve static files
app.use(express.static(path.join(__dirname, 'public')));
//parse POST data
app.use(bodyParser.urlencoded({ extended: false }));
// // parse application/json
app.use(bodyParser.json());
function after_update(err, res, record){
if (err){
res.status(500);
res.send({ error:err.toString() });
} else {
res.send(record || {});
}
}
//data loading
app.get('/data', function(req, res){
db.record.find().toArray(function(err, data){
for (var i = 0; i < data.length; i++){
data[i].id = data[i]._id;
delete data[i]._id;
}
res.send(data);
});
});
app.post('/data', function(req, res){
db.record.insert(req.body, function(err, record){
if (err) return res.send({ status:"error" });
res.send({ newid:req.body._id });
});
});
app.put('/data/:id', function(req, res){
db.record.updateById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.delete('/data/:id', function(req, res){
db.record.removeById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.listen(3000);
and I'm using index.html to display data. Here that it sucks.
my problem is that I can't found the right manner to get the data from my table in mongodb.
I want to display the cars in my DB.
who has an exemple that can help?
Anyone can help please?
Thank you
Try to load the "/data" in the browser. If it shows the valid JSON, check the client-side code of the datatable, it must be something like following
{ view:"datatable", autoConfig:true, url:"/data" }
I see 2 problems in your code (i guess that your collection is "cars" becouse your text):
You are binding a diferent collection than "cars", in the line "db.bind('sites');". You should change for "db.bind('cars');"
You are using the collection "record" to retrieve and write data, in the sentences "db.record.find", "db.record.insert", "db.record.updateById" and "db.record.removeById". You should change for "db.cars.find", "db.cars.insert", "db.cars.updateById" and "db.cars.removeById".
Cheers.
Related
On saving the code (Node JS), getting the error, 'Parsing error: Unexpected Token'
Note - Mongo connected
Tried adjusting the curly brackets and semicolon, still not working
What am I doing wrong?
Below is the code,
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
//connecting and creating a database
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//schema setup
var campgroundSchema = new mongoose.Schema({
name: String,
url: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create( {name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
function(err, campground){
if (err){
console.log(err);
}
else {
console.log("newly created campground");
console.log(campground);
}
});
var campgrounds = [
{name: "Jenny Lake", image:"https://farm2.staticflickr.com/1424/1430198323_c26451b047.jpg"},
{name: "RichardBH", image:"https://photosforclass.com/download/flickr-7626464792"},
{name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
{name: "CampAliBabaHai", image:"https://photosforclass.com/download/flickr-2770447094"},
{name: "CampAliBabaHaiYe", image:"https://photosforclass.com/download/flickr-2602356334"},
];
app.get("/", function(req, res){
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
app.post("/campgrounds", function(req, res){
var name = req.body.name
var image = req.body.image
var newcampground = {name: name, image: image}
campgrounds.push(newcampground);
res.redirect("/campgrounds");
});
app.get("/campgrounds/new" , function(req, res){
res.render("new.ejs");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("YelpCamp server started!");
});
Expected-
The file should save error-free in order to start the server and run the application
Actual-
Getting above mentioned error
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});// missing the closing brackets
});
you have miss the closing tag
On line 55, you should have an extra });
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
});
I am working on to do list app using mongoDB and node.js. Basically you type what you want to do then click add. I successfully connected the database but it doesn't show the text that's in the database. It shows only the bullets in the localhost.
Here's the code:
app.get('/', function(req, res) {
db.collection('list').find().toArray(function (err, result) {
console.log(result);
if (err) {return};
console.log(err);
res.render('index.ejs', {list: result})
});
});
app.post('/', function(req, res){
console.log(req.body);
db.collection('list').save(req.body, function(err, result) {
if (err) {return};
console.log(err);
console.log('saved')
res.redirect('/');
})
})
I have validated the code you posted and have revised it slightly with comments.
I hope this helps but it seems that the fault might be in the res.render method that is being used. Please refer to the following code:
// Requires
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
// Instantiation
var app = express();
var mongopath = "mongodb://localhost:27017/BitX";
// Port number the REST api works on
var portnum = 7500;
// MongoDB object
var db = null;
MongoClient.connect(mongopath, function(err,ldb){
db = ldb;
});
// Implement Body Parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
// Start the REST service
var server = app.listen(portnum, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
// Default route
app.get('/', function(req, res) {
// Find all items in orders and send back results to a front end
db.collection('orders').find().toArray(function (err, result) {
res.send(result);
// Consider that the rendering engine may not be functioning correctly
// SEE MORE: https://stackoverflow.com/questions/21843840/what-does-res-render-do-and-what-does-the-html-file-look-like
//res.render('index.ejs', {list: result})
});
});
// Accept a post on the root
app.post('/', function(req, res){
//Save into orders
db.collection('orders').save(req.body, function(err, result) {
res.send(true);
//res.redirect('/');
});
});
For additional information on the res.render method please have a look at:
What does "res.render" do, and what does the html file look like?
- if you have not already.
Hope it helps!
I was wondering if there was a way to check for repeated values before entering them into the database using mongodb and mongoose. I am basically looking for a way to validate the data in a sense that the data is not repeated so I don't waste space. I was hoping someone could point me in the right direction or show me a a solution, thank you.
App.js:
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
var name = req.body.name
var email = req.body.email
res.send(`You sent the name ${name} and the email ${email}`);
var user1 = {};
user1.name = name;
user1.email = email;
//validate no repeated values
collection.insert(user1, function(err,result){
if (err) {
console.log(err);
} else {
console.log('The Results', result);
db.close();
}
})
})
})
You Can use $setOnInsert
https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#op._S_setOnInsert with upsert:true.
I have this as configuration of my Express index.js:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var router = express.Router();
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'learn'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
router.get('/add', function (req, res, next){
res.render('add_costumer', {title: 'Update'});
});
router.post('/add', function (req, res){
var input = req.body;
var data = {
name : input.name,
email : input.email,
phone : input.number_phone
};
connection.query('INSERT INTO `test` SET ?', data, function(err,rows){
if(err) throw err;
console.log("Error inserting : %s ",err );
res.redirect('/');
});
});
router.get('/update', function (req, res, next){
res.render('update', {judul: 'Add'});
});
module.exports = router;
But still when I ask for req.body.something in my routes I get some error pointing Cannot read property 'name' of undefined. Here is an example of a route that uses req.body and this picture of the printing code :
output like this
Any clue?
It looks like you are requiring body-parser but not actually using it.
Depending on what kind of content you are accepting you should do:
app.use(bodyParser.json()); // where app is your express app
app.use(bodyParser.urlencoded({ extended: true});
my code at Gist: https://gist.github.com/yhagio/10654836
I'm new to Express, tried from the example of the book "Node.js in Action - Chapter.9"(Uploading photo).
The author uses Express version "3.4.0" but I used "3.4.8" and I ran into this issue,
The Error message when I try to upload images:
500 TypeError: Cannot read property 'photo' of undefined
routes/photos.js
...
exports.submit = function (dir) {
return function (req, res, next) {
var img = req.files.photo.image; // ---- This 'photo' part is undefined
var name = req.body.photo.name || img.name;
var path = join(dir, img.name);
fs.rename(img.path, path, function (err) {
if (err) { return next(err); };
Photo.create({
name:name,
path:req.name
}, function (err) {
if (err) { return next(err); };
res.redirect('/');
});
});
};
};
but I found that in my app.js (bodyParser() is no longer used since 3.4.8)
app.js(In my code Express 3.4.8)
...
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json()); // Instead of bodyParser()
app.use(express.urlencoded()); // Instead of bodyParser()
...
But in author's code has bodyParser().
app.js(Author uses Express 3.4.0
...
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); // This is no longer used in latest version
So, I was wondering if I can fix this issue by using multer (http://expressjs-book.com/forums/topic/replacement-for-bodyparser-connect-multipart/):
app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './public/photos' })); // I tried this
This didn't solve. Please help me. Thank you.
UPDATE: Solution I figured out
This code worked(routes/photos.js)
exports.submit = function (dir) {
return function(req, res, next){
var form = new multiparty.Form();
form.parse(req, function(err, fields, files){
var img = files.image[0];
var name = fields.name || img.originalFilename;
var path = join(dir, img.originalFilename);
fs.rename(img.path, path, function(err){
if(err){return next(err); };
Photo.create({
name: name,
path: img.originalFilename
}, function(err){
if(err){return next(err); };
res.redirect('/');
});
});
});
};
};
Have you given node-multiparty a try? Here's example usage from the README:
var multiparty = require('multiparty')
, http = require('http')
, util = require('util')
http.createServer(function(req, res) {
if (req.url === '/upload' && req.method === 'POST') {
// parse a file upload
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
The author (Andrew Kelley) recommends avoiding bodyParser, so you're right to avoid it, but multiparty seems to solve a similar issue for me.
The reason it no longer works is because the node-formidable library is no longer included in Express. If you want to continue using formidable, follow these instructions.
The proper way to use body-parser with Express 4.x is:
var express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
To access the files:
var formidable = require('formidable'),
form = new formidable.IncomingForm();
exports.submit = function (dir) {
return function (req, res, next) {
form.parse(req, function(err, fields, files) {
// The files object here is what you expected from req.files
});
});
});
Note: if you're trying to use multiple, set:
form.multiples = true;