I'm having some trouble getting AngularJS, Express and MongoDB to work together. I'm still new to all three of these and trying to make a simple 'to do' app and toggle a check button to mark something complete. I able to execute a function on the angular side that will do a $http 'POST' to an express route that ultimately updates a MongoDB record. I am able to do this 6 times before it stops working. I can see in the inspector console that the function is still being called, but somewhere between the $http 'POST' and executing the route, it doesn't register it anymore. I no longer see console.log activity on my Express server from the route.
Here is my toDoController.js
toDoApp.controller('ToDoController', function ToDoController($scope, $http, itemsData) {
... other functions
$scope.toggleToDo = function(item) {
console.log('updateToDo()');
console.log(item);
$http({
method: 'POST',
url: '/todolist/toggle_to_do',
data: item
}).
success(function(data, status, headers, config) {
console.log('success post');
}).
error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
}
}
Express app.js route
app.post('/todolist/toggle_to_do', todolist.toggleToDo);
Express route.js
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID; // used to create ObjectID when looking for the record
var collection
var database
// Connect to Database ------------------------------------------------
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db){
if(err) throw err;
console.log('\033[96m + \033[39m connected to mongodb');
collection = db.collection('to_do_list');
database = db;
}
);
// update record
exports.toggleToDo = function(req, res) {
console.log("-toogle 'To Do item' completed status");
console.log(req.body.completed);
console.log(req.body._id);
collection.update({
_id: new ObjectID(req.body._id)
},
{
$set: {
completed: req.body.completed
}
},
function(err) {
if(err) console.warn("Could not write to DB");
else console.log("Item successfully updated!");
}
);
};
Any help would be appreciated! Thanks!
Looks like I didn't end my response.
res.end();
exports.toggleToDo = function(req, res) {
console.log("-toogle 'To Do item' completed status");
console.log(req.body.completed);
console.log(req.body._id);
collection.update({
_id: new ObjectID(req.body._id)
},
{
$set: {
completed: req.body.completed
}
},
function(err) {
if(err) console.warn("Could not write to DB");
else console.log("Item successfully updated!");
}
);
res.end();
};
Related
I am new to node.js and trying to call an ejs file from server-side js. I am calling both the post and get methods from the client js file. Below is my code.
Client-side js:
function playerlist(){
const button = document.getElementById('playerselection');
//const data={selectedplayers:window.players};
button.addEventListener('click', function() {
console.log(players);
fetch('/FantasyTeam', {method: 'POST',
body: JSON.stringify(players),
headers: {'Content-Type':'application/json'},
})
.then(function(response) {
if(response.ok) {
CallGetMethod();
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
}
function CallGetMethod(){
console.log('Inside CallGetMethod');
fetch('/FantasyTeam', {method: 'GET'})
.then(function(response) {
if(response.ok) {
console.log('Inside response');
return ;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
**Server-side js:**
app.post('/FantasyTeam', (req, res) => {
const playerlist = req.body;
console.log(playerlist);
sql.connect(dbConfig, {
useNewUrlParser: true
}).then(() => {
// create Request object
console.log("Connected!");
var request = new sql.Request();
//Insert query to FantasyTeam Table with selected players.
request.query("INSERT Query").then(function (err, result)
{
console.log('record added to db');
}).catch(err => {
console.log('Could not insert the record to DB. Exiting now...', err);
process.exit();
});
}
res.sendStatus(201);
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
});
app.get('/FantasyTeam', (req, res) => {
// connect to your database
sql.connect(dbConfig, {
useNewUrlParser: true
}).then(() => {
// create Request object
var request = new sql.Request();
request.query("select query"), function (err, result)
{
console.log('records fetched from DB');
//res.send(result);
//res.render(path.resolve(__dirname + "/views/FantasyTeam"),{result});
res.render('FantasyTeam.ejs', { result });
//res.render('FantasyTeam.ejs', { result });
console.log(result.recordset.length);
});
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
}) ;
I tried multiple ways to render the FantasyTeam.ejs file. But couldn't succeed.There is no error in code, except that ejs file is not redered. Appreciate any help in this regard.
At first you have set view engine on your node application. Then second step create a views folder on the application root and then create a pages folder in views folder then create all template in your pages folder. views folder needs to be static. finally you can render template from pages folder in views directory. See my example. For more information visit to ejs doc: https://ejs.co/#docs
const express = require('express');
const app = express()
const router = express.Router()
// Setup View Engine and set static folder
app.use(express.static('public'))
app.set('view engine','ejs')
app.set('views','views')
//Controller
router.get('/example',(req,res,next)=>{
res.render('pages/index.ejs',{You Data})
})
I want to delete my articles. The code should be working but I couldn't understand that it doesn't work. I have created a js file to send delete issue (with ajax)
This is my delete.js:
$(document).ready(function(){
$('.delete-article').on('click', function(e){
$target = $(e.target);
const id = $target.attr('data-id');
$.ajax({
type:'DELETE',
url: '/metin/'+id,
success: function(response){
alert('Konu Siliniyor');
window.location.href='/';
},
error: function(err){
console.log(err);
}
});
});
});
This is my app.js delete route:
app.delete('/metin/:id', function(req, res){
let query = {_id: req.params.id};
Metin.remove(query, function(err){
if(err) {
console.error(err);
} else {
res.send('Success');
}
});
});
This is my article.pug:
a.button.btn.btn-danger.delete-article(href='#', data-id=metin._id) Delete
Where do I missing a code? I couldn't find it. What can I check next?
I have a node application which inserts different types of courses into mongodb and displays them onto the web page directly from the database. i want to use the fetch() api function to get the data from mongodb by passing the data into json format and then displaying them using the ejs engine
mongoose.connect('mongodb://localhost:27017/studentdb')
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
console.log("connection succeeded");
})
app.get('/', function(req, res, next) {
// fetch and sort course collection by id in descending order
req.db.collection('course').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('user/list', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('user/list', {
title: 'User List',
data: result
})
}
})
})
// SHOW ADD course FORM
app.get('/add', function(req, res, next){
// render to views/user/add.ejs
res.render('user/add', {
title: 'Add course',
topic: '',
price: '',
location: '',
provider:'',
review_rankings: '',
author_ranking: ''
})
})
app.post('/add', function(req,res, next){
var topic = req.body.topic;
var price =req.body.price;
var location = req.body.location;
var provider = req.body.provider;
var review_rankings = req.body.review_rankings;
var author_ranking =req.body.author_ranking;
var data = {
"topic": topic,
"price":price,
"location":location,
"provider":provider,
"review_rankings":review_rankings,
"author_ranking": author_ranking
};
db.collection('course').insertOne(data,function(err, collection){
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('/users');
})
I want to use the fetch api function like the code below using mongodb and displaying the information to the web page
fetch('http"//reqres.in./api/users', {
method:'POST',
headers:{
'content-type': 'application/json'
},
body: JSON.stringify({
name:'user 1'
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log('ERROR'))
The fetch API is not available out of the box for NodeJS applications. You can use the node-fetch package to get a similar API (there are some known differences though), or use other libraries like Axios.
The solution without using external packages would be to use the native http module (using the request method documented here)
Hi i'm stucked trying to create a route in the RESTful API server in express.
I've configured other routes and now i need to configure an ('/options) or ('/profile') singular route where there is only one object to retrive and update.
Basically i need to do the same of the json-server module in the Singular routes section.
So when i visit the /options endpoint i got the predefined object with this schema
{
tax: Number,
inps: Number,
ritenuta: Number,
banca: {
nome: String,
iban: String
}
}
to update.
Here's my actual routes for /options:
var Option = require('../models/option');
var express = require('express');
var router = express.Router();
router.route('/options')
.get(function(req, res) {
Option.find(function(err, options) {
if (err) {
return res.send(err);
}
res.json(options);
});
})
.post(function(req, res) {
var option = new Option(req.body);
option.save(function(err) {
if (err) {
return res.send(err);
}
res.send({message: 'Option Added'});
});
});
// Save an option
router.route('/options/:id').put(function(req, res) {
Option.findOne({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
for (prop in req.body) {
option[prop] = req.body[prop];
}
option.save(function(err) {
if (error) {
return res.send(err);
}
res.json({message: 'Option updated!'})
});
});
});
// Retrive an option
router.route('/options/:id').get(function(req, res) {
Option.findOne({ _id: req.params.id }, function(err, option) {
if (err) {
return res.send(error);
}
res.json(option);
});
});
// Delete an option
router.route('/options/:id').delete(function(req, res) {
Option.remove({ _id: req.params.id}, function(err, option) {
if (err) {
return res.send(err);
}
res.json({message: 'Option deleted!'});
});
});
module.exports = router;
but it's much complicated. It should be simpler. In fact, in this case i need to get all the options, get the id of options[0] and make a call with the id as params to retrive the object and update.
Any suggestions please?
In my ExpressJS app I have two routes to the same location, one for 'get' and one for 'post'.
On the 'get' page it dumps all the documents from my MongoDB collection, via MongooseJS, followed by a form to add a new record to the collection.
On the 'post' page it takes in the form data and adds it to the collection, and then displays the same page you see via 'get'.
It works, but after the form is submitted the new record doesn't appear unless I reload the page. I put the code that renders the page at the very bottom, below the part that adds the data to the collection so in my mind that should work but it doesn't.
exports.index = function(req, res){
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
exports.add = function(req, res){
newServer = new Server({
name: req.body.name,
os: req.body.os,
osVersion: req.body.osVersion
});
newServer.save(function (err) {
if (err) {
console.log(err);
}
});
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
Ok, I seem to make this mistake over an over again with callbacks. I fixed the problem.
exports.add = function(req, res){
newServer = new Server({
name: req.body.name,
os: req.body.os,
osVersion: req.body.osVersion
});
newServer.save(function (err) {
if (err) {
console.log(err);
} else {
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
});
}
Yes, those DB queries are async, so callbacks will solve this issue. However, you should look into using promises. Mongoose returns promises by default or you could import your library of choice. They will come in handy when dealing with nested callbacks and queries and also Error handling.