How can I display my MongoDB attributes? - javascript

I hosted my Mongo database in mLab.com with several collections as shown in the picture below:
I can't seem to be able to access "requests" collection. Here is what I have done:
first, I connected to the database and created the function in the main process (main.js):
mongoose.connect('url', { useMongoClient: true });
ipcMain.on('load-requests', function(event) {
return Requests.find({}, { sort: {createdAt: -1}});
});
Inside another file called schema.js I have the following:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var hosSchema = new Schema({
hospital: String,
state: String,
reasons: String,
requestedDateTime: String,
requestNumber: String,
status: String,
});
module.exports = mongoose.model('Requests', hosSchema);
In the renderer process (homePage.html), I have the following:
<div id="page-inner">
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="card teal">
<div class="card-content white-text">
<span class="card-title">state</span>
<p>reason</p>
</div>
<div class="card-action">
requestNumber
requestedDateTime
</div>
</div>
</div>
</div>
</div>
I want to access page-inner through its id and change the attributes to their related once in the database. For example the state should be changed with the attributes retrieved from the function in the main process (load-requests).
How can I display the attributes inside homePage.html?

In Schema.js:
var hosSchemaModel = mongoose.model('Requests', hosSchema);
module.exports = hosSchemaModel;
In main.js:
var hosSchemaModel = require("./Schema.js");
var getHosSchemas = function () {
hosSchemaModel.find({}, function (err, hosSchema) {
if (err) {
//...
} else {
//Do something with the hosSchema
}
});
}

Related

Is there a way of iterating through objects and only access certain values via their key? - Javascript

So basically, I'm making a request to the newsapi, translate the response in English and then store the translated in an object (Since I only want certain data from the response).
I'm using EJS to pass the data from backend to frontend. I've been stuck on this problem for a while now and have done countless research.
For instance, I only want to access the title in the object, pass it on to the frontend via EJS and use h1 for it. Use h3 for the description and image tag for images etc.
Here's my code:
response.on("end", function () {
const newsData = JSON.parse(newsItems);
for (let i = 0; i < newsData.articles.length; i++) {
async function quickStart() {
try {
const [translation_title] = await translate.translate(newsData.articles[i].title, 'en');
const [translation_desc] = await translate.translate(newsData.articles[i].description, 'en');
const [translation_content] = await translate.translate(newsData.articles[i].content, 'en');
const readMore = newsData.articles[i].url;
const img = newsData.articles[i].urlToImage;
const publishedAt = newsData.articles[i].publishedAt;
const emptyObjArray = {
title: translation_title,
description: translation_desc,
content: translation_content,
datePublished: publishedAt,
url: readMore,
imgURL: img
};
//Testing loop
for (const values in emptyObjArray) {
console.log(emptyObjArray);
}
res.render("newsList", { newsItem: emptyObjArray });
} catch (err) {
console.error();
}
}
quickStart();
}
});
My ejs code:
<section id="headline">
<div class="row">
<div class="col-lg-6">
<h1>Before for loop</h1>
<h1>==============</h1>
<h1><%= newsItem.title %></h1>
<h4><%= newsItem.content %></h4>
<h6>Published : <%= newsItem.datePublished %></h6>
</div>
<div class="col-lg-6">
<img src="<%= newsItem.imgURL %>" alt="" />
</div>
</div>
</section>

Filter object in Mongo database after items

I have one problem/question, how view Object from database using ng-repeat but filtering after item in this object e.g. I have ten object in products of title four computer, four TV two mobile. And my question how view this products using ng-repeat but filtering in title? I would like view separately products in different titles
Mongo Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var productSchema = new Schema({
imagePath: {
type: String,
require: true
},
title: {
type: String,
require: true,
},
subTitle: {
type: String,
require: true
},
newPrice: {
type: Number,
require : true,
}
});
module.exports = mongoose.model('Product', productSchema);
controller function
function getProducts() {
User.getProducts().then(function(data){
app.products = data.data.products;
console.log(data.data.products);
app.loading = false;
})
}
getProducts()
html view
<div ng-repeat="product in main.products" class="col-xs-12 col-sm-10" >
<div class="all_course_view slideanim">
<div class="thumbnail image_course">
<img src="../../uploads/{{ product.imagePath }}" alt="#"/>
</div>
<div class="caption">
<h3>{{ product.title }}</h3>
<h4>{{ product.subTitle }}</h4>
</div>
</div>
</div>
You can filter your results by title like so. Curtosy of AngularJS Filter Documentation.
HTML:
<p>Filter by Title: <input ng-model="search.title"></p>
<div ng-repeat="product in main.products | filter:search" class="col-xs-12 col-sm-10" >
...

fetching data from angular controller and display it on the html view got error

I am developing an online course application and I am trying to display the course details of a course along with video lectures which are on youtube.
My angular controller is fetching the course details from the node.js controller and displaying it on the html view, however it doesn't show get the youtube video link. Its because I changed the mongoose schema for storing course video from a String to String Array. If I keep the mongoose schema for course video as String, then I can view the video.
Here is the mongoose schema, file name is course.server.model.js
'use strict';
/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Course Schema
*/
var CourseSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
courseLecture: [{
week_number: { type: Number },
lecture_video: [String]
}],
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Course', CourseSchema);
In the schema, I have kept lecture_video as String array within courseLecture.
Here is my angular controller. controller name is courses.client.controller.js
(function () {
'use strict';
angular
.module('courses')
.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://www.youtube.com/**'
]);
})
.controller('CoursesController', CoursesController);
CoursesController.$inject = ['$scope', 'courseResolve', 'Authentication'];
function CoursesController($scope, course, Authentication) {
var vm = this;
vm.course = course;
vm.authentication = Authentication;
$scope.product = {
name: 'some name',
description: 'some description',
media: [{
src: vm.course.courseLecture.lecture_video
}]
};
console.log('value of courseLecture: ' + vm.course);
console.log('value of youtube embed lecture is: ' + vm.course.courseLecture.lecture_video);
$scope.getIframeSrc = function(src) {
return 'https://www.youtube.com/embed/' + src;
};
}
}());
If I do console.log for vm.course.courseLecture.lecture_video then I get undefined. However, I do get undefined for it, even from node.js controller as well.
Here is my html view. file name :- view-course.client.view.html
<style>
.video-container {
height: 400px;
width: 200px;
}
.thumbnail1 {
height: 450px;
width: 220px;
}
</style>
<section>
<div class="page-header">
<h1 ng-bind="vm.course.title"></h1>
</div>
<small>
<em class="text-muted">
Posted on
<span ng-bind="vm.course.created | date:'mediumDate'"></span>
by
<span ng-if="vm.course.user" ng-bind="vm.course.user.displayName"></span>
<span ng-if="!vm.course.user">Deleted User</span>
</em>
</small>
<p class="lead" ng-bind="vm.course.content"></p>
<div ng-repeat="media in product.media">
<div class="thumbnail1" class="col-xs-12 col-sm-9">
<div class="video-container">
<iframe ng-src="{{getIframeSrc(media.src)}}" frameborder="5" allowfullscreen></iframe>
</div>
</div>
</div>
</section>
Right now with this, I can see the course details using REST calls, only the video link doesn't work, which starts working if in the course schema, in the courseLecture property, if I change the lecture_video from lecture_video: [String] to lecture_video: {type:String}.
I can view the video. I want to store all the video links for a week in an array so the all the videos can be displayed.
Please help me with what I am doing wrong here.
If you got data according to your schema then your angular controller can be like bellow to add each video url in media. because your courseLecture is an array and in courseLecture the lecture_video also an array so need to iterate as media array so need two forEach or for loop.
$scope.product = {
name: 'some name',
description: 'some description',
media: []
};
(vm.course.courseLecture).forEach(function(lecture) {
(lecture.lecture_video).forEach(function(videoUrl) {
$scope.product.media.push({src: videoUrl});
});
});
and Html
<div ng-repeat="media in product.media">
<div class="thumbnail1 col-xs-12 col-sm-9" >
<div class="video-container">
<iframe ng-src="{{getIframeSrc(media.src)}}" frameborder="5" allowfullscreen></iframe>
</div>
</div>
</div>
Since the type has changed, there will be inconsistency in the data that is coming from rest. Hence, You have to provide backward compatibility for the string url as well as the array of string urls.
For string urls :
<div ng-if="isString(product.media)">
<div class="thumbnail1" class="col-xs-12 col-sm-9">
<div class="video-container">
<iframe ng-src="getIframeSrc(product.media.src)" frameborder="5" allowfullscreen></iframe>
</div>
</div>
</div>
For Array of string url :
<div ng-if="!isString(product.media)">
<div ng-repeat="media in product.media">
<div class="thumbnail1" class="col-xs-12 col-sm-9">
<div class="video-container">
<iframe ng-src="{{getIframeSrc(media.src)}}" frameborder="5" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
In controller :
$scope.isString = function(media){
if(Array.isArray(media)){
return false;//returns if it is an string
}
else{
return true; // return if it is an array
}
}
vm.course.courseLecture[0].lecture_video is an array which has an array of videos in the schema. In client you create $scope.product with media key which has an array value, inside is a object again with key src which should have the value vm.course.courseLecture[0].lecture_video. product.media.src[0] is the key you want to iterate.
<div ng-repeat="media in product.media.src[0]">
<div class="thumbnail1" class="col-xs-12 col-sm-9">
<div class="video-container">
<iframe ng-src="{{getIframeSrc(media)}}" frameborder="5" allowfullscreen></iframe>
</div>
</div>

How to add an array to a javascript server side model in MEAN.JS

I am using MEAN.JS and I have created a module for projects. I would like to add tasks to these projects and I would like to do it with a multi-dimensional array. I would like the array to include a task.description and a task.status which would both be strings. I think I understand the client-side part of my project and I know there are still other files. However, I believe this will make the question as simple as possible, as I am struggling to get my profile developed on this site. I will however include controller.js, so I can get this working and hopefully give credit for a correct answer.
project.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Project Schema
*/
var ProjectSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
description: {
type: String,
default: '',
trim: true
},
/* MODEL for TASK ARRAY*/
task: {
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Project', ProjectSchema);
projects.server.controller.js
'use strict';
/**
* Module dependencies.
*/
var path = require('path'),
mongoose = require('mongoose'),
Project = mongoose.model('Project'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
/**
* Create a project
*/
exports.create = function (req, res) {
var project = new Project(req.body);
project.user = req.user;
project.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(project);
}
});
};
/**
* Show the current project
*/
exports.read = function (req, res) {
res.json(req.project);
};
/**
* Update a project
*/
exports.update = function (req, res) {
var project = req.project;
project.title = req.body.title;
project.description = req.body.description;
project.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(project);
}
});
};
edit-project.client.view.html
<section ng-controller="ProjectsController" ng-init="findOne()">
<div class="page-header">
<h1>Edit Project</h1>
</div>
<div class="col-md-12">
<form name="projectForm" class="form-horizontal" ng-submit="update(projectForm.$valid)" novalidate>
<fieldset>
<div class="form-group" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="project.title" id="title" class="form-control" placeholder="Title" required>
<div ng-messages="projectForm.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Project title is required.</p>
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" ng-model="project.description" id="description" class="form-control" cols="30" rows="4" placeholder="Description"></textarea>
</div>
<div class="form-group">
Task Description
<textarea name="description" ng.model="project.task.description" class="form-control" cols="30" rows="3" placeholder="Description"></textarea>
<div>
Task Status
<input name="status" ng.model="project.task.status" class="form-control" placeholder="Status">
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
<div ng-show="error" class="text-danger">
<strong ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
First, create a model for tasks (task.server.model.js), which references a Project
var TaskSchema = new mongoose.Schema({
description: String,
status: String,
// referencing Project model
project: { type: mongoose.Schema.Types.ObjectId, ref: 'Project' }
});
And then in Project model reference Task
// Add this to Project Schema definition
tasks: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Task' }]
It's should
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Task Schema
*/
var TaskSchema = new Schema({
description: String,
status: String,
project: {
type: Schema.ObjectId,
ref: 'Project'
}
});
Hope it's help you!

Error copying req.body properties into Mongoose Model

First of all I have to say that I'm new in Angular and node technologies. So sorry for my ignorance.
I get this error when I try to save an Entity from edition view: 'Cast to ObjectId failed for value "[object Object]" at path "category"'.
Well, I've got these code:
HTML:
<form class="form-horizontal" data-ng-submit="update()" novalidate>
<fieldset>
<div class="form-group">
<label for="listaCat">Categoría:</label>
<select id="listaCat" class="form-control" data-ng-Fmodel="notification.category" data-ng-options="c.name for c in listaCategorias track by c._id">
</select>
</div>
<div class="form-group">
<label class="control-label" for="name">Descripción</label>
<div class="controls">
<input type="text" data-ng-model="notification.name" id="name" class="form-control" placeholder="Descripción" required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Guardar" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>`
Angular controller:
$scope.update = function() {
var notification = $scope.notification;
notification.$update(function() {
$location.path('notifications/' + notification._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Server side controller:
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Notification = mongoose.model('Notification'),
_ = require('lodash');
exports.update = function(req, res) {
var notification = req.notification;
notification = _.extend(notification , req.body);
notification.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(notification);
}
});
};
Mongoose Model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var NotificationSchema = new Schema({
name: {
type: String,
default: '',
required: 'Rellena la notificación',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
category: {
type: Schema.ObjectId,
ref: 'Category'
}
});
mongoose.model('Notification', NotificationSchema);
var CategorySchema = new Schema({
name: {
type: String,
default: '',
required: 'Rellena la categoría',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Category', CategorySchema);
So, if I debug inside Server controller at update method with WebStorm, I can see that req.body comes with each attribute well formed, but after convert req.body into Notification Mongoose Model with:
notification = _.extend(notification , req.body);
the category attribute is not a Model but an ObjectId. It seems as lodash.extend is not working properly for complex attributes. I've tried many other ways of cloning the object but without success.
Finally I solved it, with this line inside the angular controller:
notification.category = $scope.notification.category._id;
notification.$update(function() {
Anyway, I think that this is not the right way. I guess there must be a way of copying the req.body properties into a mongoose model without doing it manually for the complex properties.
Thanks a lot in advance!
Since you are working on AngularJS and ExpressJS, i would suggest you to use $resource service which is exactly meant for interacting with the rest API.
**$resource** contains these default set of actions:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
There is nice documentation available in the link that i shared above.
In your case:
i assume, http://localhost:300/notifications/:id, this might be your rest url where you want to perform update action.
You can create your custom services like:
var module = angular.module('myapp.services',['ngResource']);
module.factory('MyAppUpdateService',function($resource){
return $resource('notifications/:id',
{
id: '#id'
},
{
'update': { method:'PUT' }
}
);
});
Now inside your angular app controller you can inject this service as dependency and hence it will be available to perform update in that REST url.
angular.module('myapp',['ngResource','myapp.services']);
angular.module('myapp').controller('MeetupsController',['$scope','$resource','$state','$location','MeetupUpdateService','socket',
function($scope,$resource,$state,$location, MyAppUpdateService){
$scope.updateMeetup = function(){
$scope.updateService = new MyAppUpdateService();
$scope.updateService.name = $scope.notification.name;
.
.
.
$scope.updateService.$update({id:$scope.notification.category._id},function(result){
$location.path("/meetup/")
});
}
})]);
So this was just an example, if you want more comprehensive implementation. Look here, i am creating a MEAN seed of my own, and i am doing the same.
Any doubt please do ask.

Categories

Resources