How to loop a mongoosejs result and show it in handlebars? - javascript

I have the following code in my controller.
router.get('/', function(req, res, next) {
Appointment.find().then((appointments) => {
console.log(appointments);
res.render('adminappointments', { title: 'Admin-Appointments', appointlink: true, layout: 'adminlayout', appointment: appointments });
}, (err) => {
res.status(400).send(err);
})
});
And in my hbs page
<tbody>
{{#each appointmentt}}
<tr>
<td>{{this._id}}</td>
<td>{{this.name}}</td>
<td>{{this.email}}</td>
<td>{{this.purpose}}</td>
<td>{{this.clinic}}</td>
<td>{{this.message}}</td>
<td>
<button class="btn btn-small btn-inverse"><i class="icon-trash"></i> Delete</button></td>
</tr>
{{/each}}
</tbody>
The table shows no data, but console log is showing the data. Need help.

Related

Parasails JavaScript not loading after Promise resolved

I'm trying to load in data from the database dynamically with javascript and this helper function.
The function fetches a URLs which is routed to actions that return the parameters and a message after completion (as a Promise). The message gets displayed to the end user.
parasails register Page:
methods: {
loadData: async function(url) {
let origin = window.location.origin
url = new URL(origin + url);
try{
let res = await parasails.util.backendLoad(url)
console.log(res)
this.categories = res.categories
this.showResponse = res.showResponse
}catch(err){
console.log("Error: " + err)
}
},
destroyOne: async function(id) {
url = "/api/v1/category/" + id + "/destroy"
this.loadData(url);
}
}
parasails utility:
parasails.registerUtility('backendLoad', async function backendLoad(url) {
return new Promise((resolve)=>{
fetch(url)
.then((res)=>{
if (res.ok)return res.json();
throw new Error(res.status);})
.then((data)=>{
console.log(data);
resolve(data);
})
.catch((err)=>{
let resErr = []
switch(err.message){
case "401":
console.log("an error has occured of type 401");
resErr= {showResponse: {type: 'alert-danger', message "Unauthorized"}};
resolve(resErr);
default:
console.log("an error has occured");
resErr= {showResponse: {type: 'alert-danger', message: "Unkownerror"}};
resolve(resErr);
}
})
});
});
EJS:
<div id="indexCategory" v-cloak>
<div class="container my-2">
<div :class="'alert ' + showResponse.type" role="alert" v-if="showResponse">
{{showResponse.message}}
</div>
<h1>Categories</h1>
<hr/>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr scope="row" v-for="c in categories">
<td>
{{ c.name }}
</td>
<td>
<a class="btn btn-outline-secondary btn-sm" #click="destroyOne(c.id)">Delete</a>
</td>
</tr>
</tbody>
</table>
<a type="button" class="btn btn-primary mt-4" href="/category/new">Add</a>
<a type="button" class="btn btn-primary mt-4" href="/dashboard">Back to dashboard</a>
</div>
</div>
The function loadData is called beforeMount and returns all categories as it should.
When destroyOne calls the loadData function this doesnt happen. Neither the categories nor the message get shown. The action returns the parameters as expected (as a Promise).
There are no console outputs either when calling with destroyOne.
What changes do I need to implement, so that the response from destroyOne gets shown?

(Vue.js) "Uncaught (in promise) TypeError: Cannot read property 'results' of undefined"

I am trying to display data stored in a Firebase remote database in a Vue 3 webpage with a table however when I route to the display page I return the error. This is what my code looks like.
This is the HTML that displays the table:
<template>
<section v-if="!this.results.length">
No data to show
</section>
<section v-else>
<table class="table">
<thead>
<tr>
<th scope="col">View</th>
<th scope="col">Identification</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr v-for="res in results" :key="res.id">
<!-- <td><button class="btn btn-primary">View</button></td> -->
<td>{{res.idCard}}</td>
<td>{{res.name}}</td>
<td>{{res.surname}}</td>
<td>{{res.email}}</td>
<!-- <td><button class='btn btn-primary'>Update</button></td> -->
</tr>
</tbody>
</table>
</section>
</template>
And this is the Javascript. Here it is supposed to fetch the data from the firebase and push it into the results[] array.
<script>
export default {
data(){
return{
results: []
};
},
methods:{
async getData(){
console.log("Getting data");
try{
const response = await fetch("https://fir-example-56e32-default-rtdb.europe-west1.firebasedatabase.app/contact.json",{
method: 'GET'
}) //the below will parse the data thats part of the response if it is in json format; returns a promise
const responseData = await response.json();
if(!response.ok){
console.log("Something went wrong")
}
const results = [];
for (const id in responseData){
results.push({
id:id,
idCard: responseData[id].idCard,
name: responseData[id].name,
surname: responseData[id].surname,
email: responseData[id].email,
});
this.results = results;
}
}catch(error){
console.log(error);
}
},
},
//when component is fully initialised call method
mounted(){
this.getData();
}
}
</script>
the form in question
what it should look like

Get Specific Object from Array in MongoDB collection into handlebars table

I'm trying to build a table with values from an Array of objects from mongodb, but I only can get every value and only need the specific value.
So I made a query like this
router.get("/arquiveExpense", ensureAuthenticated, (req, res) => {
House.find({
userID: req.user.id,
expensesHouse: { $elemMatch: { status: "Private" } }
}).then(house => {
console.log(house);
res.render("houses/arquiveExpense", {
house: house
});
});
});
I want to retrieve the specific value from expensesHouse with status 'Private'.
And in handlebars I have this structure
<tbody>
<tr>
{{#each house}}
<td>{{expenseType}}</td>
<td>{{price}}€</td>
<td>{{payAt}}</td>
<td>{{formatDate date 'MMMM Do YYYY'}}</td>
<td>
<a href="/houses/showExpense/{{id}}" id="detailsExpense"
class="btn btn-outline-light mb-3"><i class="fas fa-eye mr-2"></i>Details
</a>
<td>
<a href="/houses/editExpense/{{id}}" id="editExpense" class="btn btn-outline-light mb-3"><i
class="fas fa-edit mr-2"></i>Edit
</td>
</tr>
{{else}}
<p>No expenses</p>
{{/each}}
</tbody>
And after this handlebars, this is the result
The Schema structure is the follow
So I want to show in the web page the value from expensesHouse with the Status 'Private'.
How can I change my code to retrieve only this value ?
Please update your code with the below, it resolves your issues with code & also with query :
router.get("/arquiveExpense", ensureAuthenticated, async (req, res) => {
try {
let house = await House.findOne({ // You can use findOne as if userID is unique
userID: req.user.id
}, { expensesHouse: { $elemMatch: { status: "Private" } } }) //$elemMatch in projection helps you to get what is needed
if (house) { // .findOne() returns null if no document found, else an object
console.log(house);
res.render("houses/arquiveExpense", {
house: house
});
} else { // No document found
console.log('No house found')
}
} catch (error) {
console.log('Error at DB call ::', error)
}
})

ng-repeat not showing any contents

I'm trying to put the content in my MongoDB using Mongoose and AngularJS. So far everything seems to be working but when I use ng-repeat the table comes up blank.
HTML code
<div class="container" ng-controller="FormController">
<table class="table table-striped">
<tbody>
<tr ng-repeat="sensordata in sensordatas track by $index">
<td>{{sensordata.topic}}</td>
<td>{{sensordata.message}}</td>
<td>{{sensordata.when}}</td>
</tr>
</tbody>
</table>
</div>
app.js
var app = angular.module('FormApp', []);
app.controller("FormController", function ($http, $scope){
$http.get("/api/sensordata")
.then(function (response) {
$scope.sensordatas = response;
});
})
server.js
//Data Schema
var dataSchema = new mongoose.Schema({
topic: String,
message: Number,
when: Date
}, {collection: "sensordata"});
var sensordata =mongoose.model('sensordata', dataSchema);
//$HTTP GET function
app.get('/api/sensordata', function(req, res) {
sensordata.find(function (err, data) {
res.json(data);
});
});
This is the data I get when I print my data to console. http://i67.tinypic.com/2rhlpwg.png I don't understand the footer of the data.
can you pleae put wrapper around your html view code for app
<div ng-app="app"><div class="container" ng-controller="FormController">
<table class="table table-striped">
<tbody>
<tr ng-repeat="sensordata in sensordatas track by $index">
<td>{{sensordata.topic}}</td>
<td>{{sensordata.message}}</td>
<td>{{sensordata.when}}</td>
</tr>
</tbody>
</table>
</div>

MongoDB array with AngularJS

I'm trying to insert data MondoDB with AngularJS's $http service , but one of the variables and the array What is in the collection , What to do ?
nome: string.
autor: string.
genero: array.
info: string.
Collection: mangas.
db.mangas.insert({nome: 'toriko', autor:'test', genero:['Ação','Aventura'], info:'...'})
Server.Js, Find mangas.
app.get('/mangas', function(req, res){
console.log('i receive a get request')
db.mangas.find(function (err, mangas){
console.log(mangas);
res.json(mangas);
});
});
Server.Js, Insert mangas.
app.post('/mangas', function (req, res) {
console.log(req.body);
db.mangas.insert(req.body, function(err, doc) {
res.json(doc);
});
});
index.html, ng-click="addManga"
<tr>
<td><input class="form-control"manga.nome></td>
<td><input class="form-control"manga.autor></td>
<td><input class="form-control"manga.genero></td>
<td><input class="form-control"manga.info></td>
<td><button class="btn btn-primary" ng-click="addManga()">Add manga</button></td> ----adiciona o metodo que se encontra no controller
</tr>
<tr ng-repeat="manga in mangas">
<td>{{manga.nome}}</td>
<td>{{manga.autor}}</td>
<td>{{manga.genero}}</td>
<td>{{manga.info}}</td>
</tr>
Controller.js
$http.get('/mangas').success(function(response) {
console.log("eu recevi a data requisitada");
$scope.mangas = response;
});
$scope.addManga = function() {
console.log($scope.mangas);
$http.post('/mangas', $scope.mangas).success(function(response) {
console.log(response);
})};
In HTML:
you should use ng-model in html to bind with controller
Like:
<td><input class="form-control" ng-model="manga.nome"></td>
instead of
<td><input class="form-control"manga.nome></td>
and in controller:
you should use $scope.manga instead of $scope.mangas because of you bind manga in html input fields.
$scope.manga = {};
$scope.addManga = function() {
console.log($scope.manga);
$http.post('/mangas', $scope.manga).success(function(response) {
console.log(response);
})};

Categories

Resources