I'm new to the stack and am building a test page to sort out my understanding before building my actual project. Right now, I'm just trying to take user input, save it to a database, and print it. The data should be saved in a basic Mongoose model, test. While all of the routes are open, instead of printing what the user entered it prints something in the following format:
{"_id":"55c3925b48b9dba0d896be40","__v":0}
I suspect it has something to do with the second line of this snippet from index.js:
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Relevent code:
All of index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
//set up routes
var mongoose = require('mongoose');
var Test = mongoose.model('Test');
router.get('/survey', function(req, res, next) {
Test.find(function(err, tests) {
if(err) {
return next(err);
}
res.json(tests);
});
});
router.post('/survey', function(req, res, next) {
var test = new Test(req.body);
test.save(function(err,test) {
if(err) {
return next(err);
}
res.json(test);
});
});
module.exports = router;
Tests.js (model):
var mongoose = require('mongoose');
var TestSchema = new mongoose.Schema({
'name': String,
});
module.exports = mongoose.model('Test', TestSchema);
Relevant bits of angular code:
routerApp.factory('tests', ['$http', function($http){
var o = {
tests: []
};
o.getAll = function() {
return $http.get('/survey').success(function(data){
console.log('get all sees data as:' + data);
angular.copy(data, o.tests);
});
};
o.create = function(test) {
console.log('create sees test as' + test);
return $http.post('/survey', test).success(function(data){
o.tests.push(data);
console.log('Data:' + data);
});
};
return o;
}]);
routerApp.controller('FormCtrl', ['$scope', 'tests',
function($scope, tests){
$scope.test = tests.tests;
$scope.addTest = function(){
if(!$scope.text || $scope.text === '') { return; }
tests.create({
name: $scope.text
});
$scope.text = '';
};
}
]);
I suspect this is a matter of not understanding what kind of object req is, but I'm not entirely positive. How would I go about making this code save data in the format described in the mongoose model?
If you call .toObject() on the document object (res.json(test.toObject())), you should get a plain object back containing the data in that document.
Try to console.log(req.body). If it's empty, then try adding app.use(bodyParser.json()) somewhere before your routes are defined (and be sure to install it with npm and require it first).
When you POST some sort of JSON, it isn't available in req.body by default. You need bodyParser to parse the incoming data and make it available in req.body. See https://medium.com/#adamzerner/how-bodyparser-works-247897a93b90 for more info.
Related
I try to understand the code of a friend and I connect to js and nodejs for the first time,I want to know the meaning of "/" , req res next.
here is the code
in routes/task.js
var express = require('express');
var router = express.Router();
var Task = require('../models/task');
router.post("/", function(req, res, next){
var task = req.body;
Task.create(task, function(err, task){
if (err) {
return res.status(400).send("err in post /task");
} else {
return res.status(200).json(task);
}
});
});
router.get("/", function(req, res, next){
Task.find({}, function(err, tasks){
if(err){
return res.status(400).send("err in get /task");
}else{
console.log(tasks);
return res.status(200).json(tasks);
}
})
});
module.exports = router;
Task is a data module exports in models/task.js
var mongoose = require('mongoose');
var TaskSchema = new mongoose.Schema({
title: String,
create_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Task", TaskSchema);
This is to attach HTTP method request handlers using Express's router object for the webapp.
This is my controller.js
$scope.saveDetails = function(){
if($scope.editMode == false){
//$scope.hidesave = false;
//$scope.person = "";
console.log("i am in save")
console.log($scope.person);
$http.post('/details',$scope.person).success(function(response){
console.log(response);
refresh();
})
$state.go("itemList");
This is my Route.JS
module.exports = function (app){
console.log("Inside Routes");
app.get('/details', require('./details/details').getDetails);
app.get('/details/:id', require('./details/details').getDetails_id);
app.post('/details', require('./details/details').saveDetails);
app.delete('/details/:id',require('./details/details').deleteDetails);
app.post('/details/:id',require('./details/details').updateDetails);
};
This is my details.js wher actual implementation is :
exports.saveDetails = function (req, res) {
console.log("Hi");
console.log("this is to save: ",req.body);
var person = new req.app.schema.detailsdb(req.body);
person.save(req.body,function(err,docs){
res.json(docs);
console.log("docs: ",docs)
});
};
Here req.body returns undefined when i try to insert data from HTML Page to DB , i have written DB using Mongoose
To parse JSON you need to include the express body-parser module and use it before your routes:
var bodyParser = require('body-parser')
// parse application/json
app.use(bodyParser.json())
// the rest of your routes here.
app.get('/details', require('./details/details').getDetails);
app.get('/details/:id', require('./details/details').getDetails_id);
app.post('/details', require('./details/details').saveDetails);
app.delete('/details/:id',require('./details/details').deleteDetails);
app.post('/details/:id',require('./details/details').updateDetails);
https://github.com/expressjs/body-parser/blob/master/README.md
I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;
$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything
Currently using MEAN in order to connect my AngularJS app to a database.
I have a button called "commit to database" that first clears the mongodb database, then inserts my array of data (stored in $scope.filterTable) into the database.
I then have a button called "load from database" that updates $scope.filtertable to match data from the database.
Half of the time when I click the "commit to database" button, my database is empty. Half of the time, it's filled with the data I expect it to have.
Anyone know what I'm doing wrong? Thanks!
Here's the code in my main AngularApp:
var commitToDatabase = function(){
deleteDatabase();
insertDatabase();
}
var insertDatabase = function(){
$http.post("/AngularApp", $scope.filterTable).success(function(response){
$http.get('/AngularApp').success(function(response) {
console.log(response);
});
});
}
var deleteDatabase = function(){
$http.delete('/AngularApp');
}
var loadFromDatabase = function(){
$http.get('/AngularApp').success(function(response) {
$scope.filterTable = response;
});
}
Here's the code in my server.js file:
var express = require("express");
var mongojs = require("mongojs");
var bodyParser = require("body-parser");
var app = express();
var db = mongojs("AngularApp", ["AngularApp"]);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/AngularApp', function (req, res) {
console.log('I received a GET request');
db.AngularApp.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/AngularApp', function (req, res) {
console.log("POST");
console.log(req.body);
db.AngularApp.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/AngularApp', function(req, res){
db.AngularApp.remove({},function(err, doc){
res.json(doc);
});
});
app.listen(3000);
console.log("Server running on point 30000");
My purpose is to create a realtime counter. Actually I'm creating files with my server. And I want for every created file, the counter to be incremented (the client should see the number of files in the browser growing...)
How can I exactly do that using Socket.io, AngularJS and Express.js ?
P.S : I have already written some code, but vainly.
EDIT 1 :
public/core.js
var app = angular.module('app', []);
app.factory('socket', function($rootScope){
var socket = io.connect();
return{
on: function(eventName, callback){
socket.on(eventName, function(){
var args = arguments;
$rootScope.$apply(function(){
callback.apply(socket, args);
});
});
},
emit: function(eventName, data, callback){
socket.emit(eventName, data, function(){
var args = arguments;
$rootScope.$apply(function(){
if(callback){
callback.apply(socket.args);
}
});
})
}
};
});
function mainController($scope, $http, socket) {
$scope.formData = {};
socket.on('number', function (data) {
console.log("Socket on number core.js !");
$scope.number = data.numberOfFiles;
});
$scope.initialize = function() {
$scope.formData.search = "";
console.log("initialize() body !");
};
$scope.search = function() {
socket.emit('next', {
message: "next"
});
console.log("search() body !");
$http.post('/search', $scope.formData)
.success(function() {
$('input').val('');
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
app.js
/**
* Module dependencies.
*/
var express = require('express');
var request = require('request');
var http = require('http');
var path = require('path');
var url = require('url');
var cheerio = require('cheerio'); // builds the DOM tree
var fs = require('fs');
var app = express();
// all environments
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // pull information from html in POST
app.use(express.methodOverride()); // simulate DELETE and PUT
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
});
// app.listen(8080);
// console.log("App listening on port 8080");
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);
var numberFiles = 1;
app.post('/search', function(req, res){
var keyword = req.body.search;
for(var i = 0; i < 100; i++) {
// The results' page URL
// some long logic that creates files and increments numberFiles
numberFiles++;
}
});
io.sockets.on('connection', function (socket) {
socket.on('next', function (data) {
socket.emit('number', {
numberOfFiles: numberFiles
});
});
});
app.get('/', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
Have you tried:
SERVER
io.sockets.on('connection', function (socket) {
socket.on('next', function (data, respond) {
respond({
numberOfFiles: numberFiles
});
});
});
CLIENT
socket.emit('next', {
message: "next"
}, function(data){ // data.numberOfFiles ... };