JSON to CSV does not skip commas in strings - javascript

I want to implement JSON to CSV on my server but I am facing an issue with entries that contain commas, as comma is my separator.
This result in some content not being in the corresponding columns.
How can I skip commas when they are in an entry thus in a string.
Thanks
function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;
data.forEach(function (item) {
ctr = 0;
keys.forEach(function (key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
}
function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV({
data: activitesExport
});
if (csv == null) {
console.log("CSV null");
return;
}
filename = args.filename || 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}
A sample of how my data looks like :
{
"-LSKp07UQ7TAEXYxK6Li" : {
"activiteId" : "-LSKp07UQ7TAEXYxK6Li",
"adresseCodePostal" : "38340",
"adresseVille" : "VOREPPE",
"adresseVoie" : " 517 rue de Nardan",
"ageMaximum" : "",
"ageMinimum" : "",
"categorie" : "CULTURE",
"description" : "l’Arrosoir est un équipement destiné à accueillir de nombreux événements festifs et culturels tout au long de l’année.",
"divers" : "",
"horaires" : "Horaires divers en fonction des événements",
"illustration" : "https://firebasestorage.googleapis.com/",
"indoor" : true,
"latitude" : 45.2916646,
"longitude" : 5.6349276,
"nom" : "L’arrosoir",
"outdoor" : false,
"siteWeb" : "",
"tarifs" : "En fonction de la manifestation",
"telephone" : "0476504747"
},
"-LSKpWYf9fPaBjtU578e" : {
"activiteId" : "-LSKpWYf9fPaBjtU578e",
"adresseCodePostal" : "38340",
"adresseVille" : "VOREPPE",
"adresseVoie" : "Rue Jean Achard,",
"ageMaximum" : "",
"ageMinimum" : "",
"categorie" : "LOISIRS",
"description" : "Deux terrains de 4 jeux pour la boule lyonnaise ou la pétanque.",
"divers" : "",
"horaires" : "Accès libre ",
"illustration" : "https://firebasestorage.googleapis.com/",
"indoor" : false,
"latitude" : 45.296335,
"longitude" : 5.6363899,
"nom" : "Gradins de la verronière",
"outdoor" : true,
"siteWeb" : "https://www.voreppe.fr/article/terrains-de-boule",
"tarifs" : "gratuit",
"telephone" : "0476504747"
}
}

I've had to do something very similar with big data text rows
I'd suggest using this library
https://www.npmjs.com/package/csv-stringify
Here's a function i wrote to create a CSV from 'dirty' arrays using csv-stringify
export const convertToCSV = (output: string[][]) => {
return new Promise ((resolve,fail) => {
stringify(output, (err, outputData) => {
if (!err) {
resolve(outputData as string[][]);
} else {
fail(err);
}
});
})
}

Related

Not able to pass Multiple image to Server Nodejs

I have created an application using an android studio and for server-side using NodeJs.I have tried to pass a single image and able to pass. This time, I want to pass multiple images to the server, but when I started change parameter from image:MultipleBody.Part to images:List<MultipartBody.Part> at Api.kt file, received an error message at the server-side. I don't know with a part that I'm doing it wrong. Hope can help me solve this problem. Thank you in advance.
$ node app Listening on port 4545... MulterError: Unexpected field
at wrappedFileFilter (C:\Users\user\Documents\GitHub\EIS-API\node_modules\multer\index.js:40:19)
at Busboy. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\multer\lib\make-middleware.js:114:7)
at Busboy.emit (events.js:223:5)
at Busboy.emit (C:\Users\user\Documents\GitHub\EIS-API\node_modules\busboy\lib\main.js:38:33)
at PartStream. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\busboy\lib\types\multipart.js:213:13)
at PartStream.emit (events.js:223:5)
at HeaderParser. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\Dicer.js:51:16)
at HeaderParser.emit (events.js:223:5)
at HeaderParser._finish (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\HeaderParser.js:68:8)
at SBMH. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\HeaderParser.js:40:12)
MulterError: Unexpected field
at wrappedFileFilter (C:\Users\user\Documents\GitHub\EIS-API\node_modules\multer\index.js:40:19)
at Busboy. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\multer\lib\make-middleware.js:114:7)
at Busboy.emit (events.js:223:5)
at Busboy.emit (C:\Users\user\Documents\GitHub\EIS-API\node_modules\busboy\lib\main.js:38:33)
at PartStream. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\busboy\lib\types\multipart.js:213:13)
at PartStream.emit (events.js:223:5)
at HeaderParser. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\Dicer.js:51:16)
at HeaderParser.emit (events.js:223:5)
at HeaderParser._finish (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\HeaderParser.js:68:8)
at SBMH. (C:\Users\user\Documents\GitHub\EIS-API\node_modules\dicer\lib\HeaderParser.js:40:12)
Api.kt
#Multipart
#POST("perkhidmatan_rumput/api/PostPemantauanPerkhidmatanPotingRumput" +
"/{zon}/{syarikat}/{alamat_syarikat}/{nama_penyelia}/{taman}/{bulan}/{tahun}" +
"/{masa}/{timeAMPM}/{pusingan}/{status}/{catatan}/{state}/{entryOperator}")
fun postPemantauanPerkhidmatanPotingRumput(
#Path("zon")zon:String,
#Path("syarikat")syarikat:String,
#Path("alamat_syarikat")alamat_syarikat:String,
#Path("nama_penyelia")nama_penyelia:String,
#Path("taman")taman:Int,
#Path("bulan")bulan:String,
#Path("tahun")tahun:String,
#Path("masa")masa:String,
#Path("timeAMPM")timeAMPM:String,
#Path("pusingan")pusingan:String,
#Path("status")status:String,
#Path("catatan")catatan:String,
#Path("state")state:String,
#Path("entryOperator")entryOperator:String,
#Part images:List<MultipartBody.Part>
//#Part image:MultipartBody.Part?
):LiveData<GenericApiResponse<OnResponse>>
PemoViewModel.kt
public fun getAllImages():List<MultipartBody.Part>?{
var info = getCurrentViewStateOrNew()
var pic:List<GambarSebelum>? = info.gambarSebelum
var images = mutableListOf<MultipartBody.Part>()
pic?.let {
for ( item in it){
var multipartBody: MultipartBody.Part? = null
item.url?.path?.let { filePath ->
val imageFile = File(filePath)
val requestBody =
RequestBody.create(
MediaType.parse("image/*"),
imageFile
)
multipartBody = MultipartBody.Part.createFormData(
"image",
imageFile.name,
requestBody
)
}
images.add(multipartBody!!);
}
}
return images;
}
PemoFragment.kt
_binding.btnLogin.setOnClickListener {
if(!isFill()){
Toast.makeText(requireContext(),"sila penuhkan ruang diatas..",Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
var bulan:String = CALENDER.valueOf(_binding.idBulanSpinner.selectedItem.toString()).value
var taman:Int? = _viewModel.getTamanIdByTamanName(_binding.idTamanSpinner.selectedItem.toString())
var pusingan:String? = _viewModel.getPusinganByPusinganName(_binding.idPusinganSpinner.selectedItem.toString())
var status:String? = _viewModel.getStatusByStatusName(_binding.idStatusSpinner.selectedItem.toString())
var images:List<MultipartBody.Part>? = _viewModel.getAllImages()
if(taman != null && pusingan != null && status != null){
//insert information to server (database)
_viewModel.setStateEvent(
FormRumputStateEvent.SubmitPemantauanForm(
PemantauanPotongRumputResponse(
_binding.idZonsSpinner.selectedItem.toString(),
_binding.idNamaSyarikatEdit.text.toString(),
_binding.idAlamatSyarikat.text.toString(),
_binding.idNamaPenyeliaKontraktorEdit.text.toString(),
taman,
bulan,
_binding.idTahunEdit.text.toString(),
_binding.idMasaEdit.text.toString(),
_binding.idAmPmSpinner.selectedItem.toString(),
pusingan,
status,
_binding.idCatatanEdit.text.toString(),
STATE_STATUS.CREATE.name,
"ADMIN",
images!!
)
))
}else{
Toast.makeText(requireContext(),"[Error] Taman,Bulan,pusingan or status has Problem..",Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
}
PemantauanPotongRumputResponse
data class PemantauanPotongRumputResponse(
#Expose
#SerializedName("zon")
val zon:String,
#Expose
#SerializedName("syarikat")
val syarikat:String,
#Expose
#SerializedName("alamat_syarikat")
val alamat_syarikat:String,
#Expose
#SerializedName("nama_penyelia")
val nama_penyelia:String,
#Expose
#SerializedName("taman")
val taman:Int,
#Expose
#SerializedName("bulan")
val bulan:String,
#Expose
#SerializedName("tahun")
val tahun:String,
#Expose
#SerializedName("masa")
val masa:String,
#Expose
#SerializedName("timeAMPM")
val timeAMPM:String,
#Expose
#SerializedName("pusingan")
val pusingan:String,
#Expose
#SerializedName("status")
val status:String,
#Expose
#SerializedName("catatan")
val catatan:String,
#Expose
#SerializedName("state")
val state:String,
#Expose
#SerializedName("entryOperator")
val entryOperator:String,
#Expose
#SerializedName("images")
val images:List<MultipartBody.Part>
)
SERVER SIDE
NODE.JS
router.post('/api/PostPemantauanPerkhidmatanPotingRumput/:zon/:syarikat/:alamat_syarikat/'+
':nama_penyelia/:taman/:bulan/:tahun/:masa/:timeAMPM/:pusingan/:status/:catatan/:state/'+
':entryOperator', upload.array('images',9),(req,res,next) =>{
try{
const file = req.files;
if (!file) {
res.status(400).json({
"status": "failed",
"code" : "400",
"message" : "Please upload file"
});
}
res.status(200).json({
"status": "success",
"code" : "200",
"message" : "file uploaded successfully"
});
console.log(file);
console.log(req.body);
}catch(err){
console.log(error.message);
res.status(200).json({
"status": "failed",
"code" : "500",
"message" : error.message
});
}
})
Able to Solved the problem. Just make sure the first parameter "images" at MultipartBody.Part.createFormData same at Server-Side parameter upload.array("images")
multipartBody = MultipartBody.Part.createFormData(
"images",
imageFile.name,
requestBody
)
PemoViewMode.kt
public fun getAllImages():List<MultipartBody.Part>?{
var info = getCurrentViewStateOrNew()
var pic:List<GambarSebelum>? = info.gambarSebelum
var images = mutableListOf<MultipartBody.Part>()
pic?.let {
for ( item in it){
var multipartBody: MultipartBody.Part? = null
item.url?.path?.let { filePath ->
val imageFile = File(filePath)
val requestBody =
RequestBody.create(
MediaType.parse("image/*"),
imageFile
)
multipartBody = MultipartBody.Part.createFormData(
"images",
imageFile.name,
requestBody
)
}
images.add(multipartBody!!);
}
}
return images;
}
SERVER-SIDE (NODEJS)
router.post('/api/PostPemantauanPerkhidmatanPotingRumput/:zon/:syarikat/:alamat_syarikat/'+
':nama_penyelia/:taman/:bulan/:tahun/:masa/:timeAMPM/:pusingan/:status/:catatan/:state/'+
':entryOperator', upload.array('images',9),(req,res,next) =>{
try{
const file = req.files;
if (!file) {
res.status(400).json({
"status": "failed",
"code" : "400",
"message" : "Please upload file"
});
}
res.status(200).json({
"status": "success",
"code" : "200",
"message" : "file uploaded successfully"
});
console.log(file);
console.log(req.body);
}catch(err){
console.log(error.message);
res.status(200).json({
"status": "failed",
"code" : "500",
"message" : error.message
});
}
})

I can't connect vue to my Laravel blade view

I am trying to connect my app vue with Laravel, I was able to achieve it with the "users" route but when trying to connect the second part, I can't do it, it just doesn't allow me to connect, I don't know if I'm doing things wrong, I'm new using vue.
When I connect #crudUsuarios everything works but when I connect #crudLessons data is not shown.
I tried the routes and they actually work, they return the data I want, however when connected it shows nothing.
I also get an error in the view that is not where it shows "#crudUsarios"
Error: app.js: 2626 [Vue warn]: Cannot find element: #crudUsuarios
app.js
// require('./bootstrap');
window.Vue = require('vue');
window.moment = require('moment');
window.axios = require('axios');
// import toastr from 'toastr'
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('example-component', require('./components/ExampleComponent.vue'));
const app = new Vue({
el: '#crudUsuarios',
created: function()
{
this.getUsers();
},
data: {
time: moment().format('Y-M-d H:mm:ss'),
users: [],
newName: '', newfLastName : '', newsLastName : '', newAge : '', newEmail: '', newCellphone : '', newPassword: '',
fillUser: {'id' : '', 'slug': '', 'name' : '','fLastName' : '','sLastName' : '','age' : '','email' : '', 'cellphone' : '', 'password' : ''},
getUser: {'id' : '', 'slug': '','name' : '','fLastName' : '','sLastName' : '','age' : '','email' : '', 'cellphone' : '', 'password' : ''},
errors: []
},
methods: {
getUsers: function()
{
//Aqui es donde conecta a la ruta para jalar los datos
var urlUsers = 'users';
axios.get(urlUsers).then(response =>{
this.users = response.data
});
},
editUser: function(user){
this.fillUser.id = user.id;
this.fillUser.name = user.name;
this.fillUser.fLastName = user.fLastName;
this.fillUser.sLastName = user.sLastName;
this.fillUser.age = user.age;
this.fillUser.email = user.email;
this.fillUser.cellphone = user.cellphone;
this.fillUser.password = user.password;
$('#edit').modal('show');
},
updateUser: function(id){
// alert('Nada man');
var url = 'users/' + id;
axios.put(url, this.fillUser).then(response => {
this.getUsers();
this.fillUser = {'id' : '','name' : '','fLastName' : '','sLastName' : '','age' : '','email' : '', 'cellphone' : '', 'password' : ''};
this.errors = [];
$('#edit').modal('hide');
toastr.success('Usuario actualizado con éxito');
}).catch(error => {
this.errors = error.response.data
});
},
deleteUser: function(user)
{
var url = 'users/' + user.id;
if (confirm("¿Eliminar usuario?") == true) {
axios.delete(url).then(response => {
this.getUsers();
toastr.success('Usuario eliminado con éxito');
});
} else {
this.getUsers();
}
},
createUser: function()
{
var url = 'users';
axios.post(url, {
name: this.newName,
fLastName: this.newfLastName,
sLastName: this.newsLastName,
age: this.newAge,
email: this.newEmail,
cellphone: this.newCellphone,
password: this.newPassword
}).then(response => {
this.getUsers();
//Vaciar los campos de creacón una vez creado el usuario.
this.newName= '', this.newfLastName= '', this.newsLastName = '', this.newAge = '', this.newEmail= '', this.newCellphone = '', this.newPassword= '',
this.errors = [];
$('#create').modal('hide');
toastr.success('Nuevo usuario creado con éxito');
// Código para que no se quede activo el MODAL
if ($('.modal-backdrop').is(':visible')) {
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
};
}).catch(error => {
this.errors = error.response.data
});
},
showUser: function (user) {
var url = 'users/'+user.id;
axios.get(url).then(response =>{
// alert('nada de nada');
this.getUser.id = user.id;
this.getUser.slug = user.slug;
this.getUser.name = user.name;
this.getUser.fLastName = user.fLastName;
this.getUser.sLastName = user.sLastName;
this.getUser.age = user.age;
this.getUser.email = user.email;
this.getUser.cellphone = user.cellphone;
this.getUser.password = user.password;
this.getUser.created_at = user.created_at;
$('#show').modal('show');
});
}
}
});
// /var urlUsers = 'https://randomuser.me/api/?results=10';
const app = new Vue({
el: '#crudLessons',
created: function()
{
this.getLessons();
},
data: {
lessons: [],
// newName: '', newfLastName : '', newsLastName : '', newAge : '', newEmail: '', newCellphone : '', newPassword: '',
// fillUser: {'id' : '','name' : '','fLastName' : '','sLastName' : '','age' : '','email' : '', 'cellphone' : '','password' : ''},
getLesson: {'id' : '','fecha' : '','inicio' : '','final' : '', 'user_name' : '', 'user_fLastName' : '', 'user_sLastName' : '', 'user_email' : '', 'user_cellphone' : '', 'created_at' : ''},
errors: []
},
methods: {
getLessons: function()
{
//Aqui es donde conecta a la ruta para jalar los datos
var urlLessons = 'lessons';
axios.get(urlLessons).then(response =>{
this.lessons = response.data
});
},
}
});
index.blade.php
#extends('layouts.material')
#section('content')
<div class="col-lg-12" id="crudLessons">
<div class="card">
<h4> #{{ $data }} </h4>
</div>
</div>
#endsection
LessonsController.php
public function index()
{
// $products = Lesson::orderBy('id', 'DESC')->get();
$products = Lesson::with('user')->OrderBy('id', 'DESC')->get();
return $products;
}
You need to have a div with an ID corresponding to the ID you're attaching the Vue instance to using the el attribute
<div id="crudUsuarios">
#{{ data }}
</div>
Side Note
You're defining const app as a Vue Instance twice in your app.js
A constant should only exist once by the same name

Select all in datatable with angular js

I use this code in my application and I can' t select all:
'use strict';
/**
* #ngdoc function
* #name INSIDERSApp.controller:ReferentCtrl
* #description
* # ReferentCtrl
* Controller of the INSIDERSApp
*/
angular.module('INSIDERSApp')
.controller('ReferentCtrl', function (INSIDERSServices,$log,$scope,DTOptionsBuilder, DTColumnBuilder, $q,$filter) {
$scope.referents = this;
$scope.referents.selected = {};
$scope.referents.selectAll = false;
$scope.referents.toggleAll = toggleAll;
$scope.referents.toggleOne = toggleOne;
var titleHtml = '<input type="checkbox" ng-model="referents.selectAll" ng-click="referents.toggleAll(referents.selectAll, referents.selected)">';
$scope.referents.dtOptions = DTOptionsBuilder
.fromFnPromise(function() {
var defer = $q.defer();
INSIDERSServices.referents()
.success(function(data){
defer.resolve(data);
}).error(function(data){
$log.error("ERROR can't get liste of referents");
});
return defer.promise;
})
.withPaginationType('full_numbers')
.withLightColumnFilter({
'1' : {
type : 'text'
},
'2' : {
type : 'text'
},
'3' : {
type : 'text'
},
'4' : {
type : 'text'
},
'5' : {
type : 'text'
},
'6' : {
type : 'text'
},
'7' : {
type : 'text'
},
'8' : {
type : 'text'
}
})
.withOption('paging', true)
.withOption('searching', true)
.withOption('info', true)
.withLanguageSource('app/styles/plugins/datatables/json/French.json')
.withDOM(
"<'row'<'col-sm-7'l><'col-sm-5'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-7'i><'col-sm-5'p>>"
)
;
$scope.referents.dtColumns = [
DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function (data, type, full, meta) {
$scope.referents.selected[full.id] = false;
return '<input type="checkbox" ng-model="referents.selected[' + data.id + ']" ng-click="referents.toggleOne(referents.selected)">';
}),
DTColumnBuilder.newColumn('nom').withTitle('Nom'),
DTColumnBuilder.newColumn('prenom').withTitle('Prénom'),
DTColumnBuilder.newColumn('fonction').withTitle('Fonction'),
DTColumnBuilder.newColumn('profil').withTitle('Profil'),
DTColumnBuilder.newColumn('etat').withTitle('MAJ Liste').renderWith(function(data, type) {
if(data === true) return "Oui";
else return "Non";
}),
DTColumnBuilder.newColumn('dateMaj').withTitle('Date de MAJ Liste').renderWith(function(data, type) {
return $filter('date')(data, 'dd/MM/yyyy'); //date filter
}),
DTColumnBuilder.newColumn('dateRelance').withTitle('Date de relance').renderWith(function(data, type) {
return $filter('date')(data, 'dd/MM/yyyy'); //date filter
}),
DTColumnBuilder.newColumn('dateNotif').withTitle('Date de Notification').renderWith(function(data, type) {
return $filter('date')(data, 'dd/MM/yyyy'); //date filter
})
];
function toggleAll (selectAll, selectedItems) {
$log.log("IN toggleAll");
for (var id in selectedItems) {
if (selectedItems.hasOwnProperty(id)) {
selectedItems[id] = selectAll;
}
}
}
function toggleOne (selectedItems) {
$log.log("IN toggleOne");
for (var id in selectedItems) {
if (selectedItems.hasOwnProperty(id)) {
if(!selectedItems[id]) {
$scope.referents.selectAll = false;
return;
}
}
}
$scope.referents.selectAll = false;
}
});
<div class="main-container content-active">
<div class="content">
<div ng-controller="ReferentCtrl as referents">
<p class="text-danger">You selected the following rows:</p>
<p>
</p><pre>{{ referents.selected |json }}</pre>
<p></p>
<table datatable="" dt-options="referents.dtOptions" dt-columns="referents.dtColumns" width="100%" class="table table-striped table-bordered"></table></div> </div>
I follow this tutorial:
[enter image description here][1]
http://l-lin.github.io/angular-datatables/archives/#!/rowSelect
Any help please but it doesn't work!!
i find the solution:
I add 'createdRow' and 'headerCallback' in my code and $compile in my Controller function:
'use strict';
/**
* #ngdoc function
* #name INSIDERSApp.controller:ReferentCtrl
* #description # ReferentCtrl Controller of the INSIDERSApp
*/
angular
.module('INSIDERSApp')
.controller(
'ReferentCtrl',
function(INSIDERSServices,$compile, $log, $scope, DTOptionsBuilder,
DTColumnBuilder, $q, $filter) {
$scope.referents = this;
$scope.referents.selected = {};
$scope.referents.selectAll = false;
$scope.referents.toggleAll = toggleAll;
$scope.referents.toggleOne = toggleOne;
var titleHtml = '<input type="checkbox" ng-model="referents.selectAll" ng-click="referents.toggleAll(referents.selectAll, referents.selected)">';
$scope.referents.dtOptions = DTOptionsBuilder
.fromFnPromise(
function() {
var defer = $q.defer();
INSIDERSServices
.referents()
.success(function(data) {
defer.resolve(data);
})
.error(
function(data) {
$log
.error("ERROR can't get liste of referents");
});
return defer.promise;
})
.withPaginationType('full_numbers')
.withLightColumnFilter({
'1' : {
type : 'text'
},
'2' : {
type : 'text'
},
'3' : {
type : 'text'
},
'4' : {
type : 'text'
},
'5' : {
type : 'text'
},
'6' : {
type : 'text'
},
'7' : {
type : 'text'
},
'8' : {
type : 'text'
}
})
.withOption('paging', true)
.withOption('searching', true)
.withOption('info', true)
.withOption('createdRow', function(row, data, dataIndex) {
$compile(angular.element(row).contents())($scope);
})
.withOption('headerCallback', function(header) {
if (!$scope.referents.headerCompiled) {
$scope.referents.headerCompiled = true;
$compile(angular.element(header).contents())($scope);
}
})
.withLanguageSource(
'app/styles/plugins/datatables/json/French.json')
.withDOM(
"<'row'<'col-sm-7'l><'col-sm-5'f>>"
+ "<'row'<'col-sm-12'tr>>"
+ "<'row'<'col-sm-7'i><'col-sm-5'p>>");
$scope.referents.dtColumns = [
DTColumnBuilder
.newColumn(null)
.withTitle(titleHtml)
.notSortable()
.renderWith(
function(data, type, full, meta) {
$scope.referents.selected[full.id] = false;
return '<input type="checkbox" ng-model="referents.selected['
+ data.id
+ ']" ng-click="referents.toggleOne(referents.selected)">';
}),
DTColumnBuilder.newColumn('nom').withTitle('Nom'),
DTColumnBuilder.newColumn('prenom').withTitle(
'Prénom'),
DTColumnBuilder.newColumn('fonction').withTitle(
'Fonction'),
DTColumnBuilder.newColumn('profil').withTitle(
'Profil'),
DTColumnBuilder.newColumn('etat').withTitle(
'MAJ Liste').renderWith(
function(data, type) {
if (data === true)
return "Oui";
else
return "Non";
}),
DTColumnBuilder.newColumn('dateMaj').withTitle(
'Date de MAJ Liste').renderWith(
function(data, type) {
return $filter('date')(data,
'dd/MM/yyyy'); // date filter
}),
DTColumnBuilder.newColumn('dateRelance').withTitle(
'Date de relance').renderWith(
function(data, type) {
return $filter('date')(data,
'dd/MM/yyyy'); // date filter
}),
DTColumnBuilder.newColumn('dateNotif').withTitle(
'Date de Notification').renderWith(
function(data, type) {
return $filter('date')(data,
'dd/MM/yyyy'); // date filter
}) ];
function toggleAll(selectAll, selectedItems) {
$log.log("IN toggleAll");
for ( var id in selectedItems) {
if (selectedItems.hasOwnProperty(id)) {
selectedItems[id] = selectAll;
}
}
}
function toggleOne(selectedItems) {
$log.log("IN toggleOne");
for ( var id in selectedItems) {
if (selectedItems.hasOwnProperty(id)) {
if (!selectedItems[id]) {
$scope.referents.selectAll = false;
return;
}
}
}
$scope.referents.selectAll = true;
}
});
<div class="main-container content-active">
<div class="content">
<div ng-controller="ReferentCtrl as referents">
<p class="text-danger">You selected the following rows:</p>
<p>
</p><pre>{{ referents.selected |json }}</pre>
<p></p>
<table datatable="" dt-options="referents.dtOptions" dt-columns="referents.dtColumns" width="100%" class="table table-striped table-bordered dataTable no-footer"></table>
</div>
</div>
</div>

Update collection using email inplace of _Id as the unique Id

I have 2 collection tables that only share emails as the unique ids of these 2 tables. The first one is Meteor.users() and SchoolStudents. I want to update the SchoolStudents collection based on the user's email. Though I have successfully updated using _id but the update isn't working using email as the Id. What's the better approach?
In this, it returned a success feedback but no update is made to the record. Bert.alert('Record updated successfully', 'success', 'growl-top-right');
Client code:
let user = Meteor.user();
let studentemail = user && user.emails && user.emails[0].address;
if (studentemail) {
console.log(studentemail);
Meteor.call('UpdateUser', studentemail, function (error, response) {
if (error) {
Bert.alert(error.reason, 'danger', 'growl-top-right');
return false;
} else {
Bert.alert('Record updated successfully', 'success', 'growl-top-right');
}
})
}
Server method
SchoolStudents.update({useremail: studentemail}, {$set: {'status.active': true, 'status.activedate': new Date()}});
This is a sample document from the SchoolStudents collection:
{
"_id" : "xgxZJFRkXGhHmHupY",
"firstname" : "Kehinde",
"lastname" : "Adeoya",
"middlename" : "Adekusibe",
"username" : "ken10ward",
"password" : "PvyLwY9d",
"useremail" : "kadeoya#appzonegroup.com",
"studentclass" : "ss8",
"dateofbirth" : "9-Mar-00",
"gender" : "f",
"ethinicity" : "black",
"mobile" : "8023472442",
"address" : "7 Abrahamoivc",
"city" : "bolson",
"lg" : "loveland",
"state" : "ekiti",
"country" : "Ukraine",
"registra" : "kadeoya",
"status" : {
"active" : false,
"activedate" : null
},
"userId" : "n5rqFSHbhm7zqADyB",
"createdAt" : ISODate("2017-09-05T18:45:14.877Z"),
"friendlySlugs" : {
"slug" : {
"base" : "kehinde-adeoya",
"index" : 5
}
},
"slug" : "kehinde-adeoya-5"
}
This is the server update code:
UpdateUser: function (studentemail) {
check(studentemail, String);
if (!Meteor.userId()) {
Meteor.Error('Not authorized');
return false;
} else {
SchoolStudents.update({useremail: studentemail}, {status: {active: true, activedate: new Date()}}, { upsert: true });
}
}
As it has been pointed to you, you're using user && user.emails && user.emails[0].address construct wrong way.
I suggest you to use this template to do things like that:
let studentemail;
try {
studentemail = user.emails[0].address.valueOf();
} catch (e) {
studentemail = null;
}
if (studentemail != null) {
...
}
This way you can omit numerous checks, like user != null and user.emails != null and user.emails.length > 0 etc and it will be guaranteed that in your studentemail variable you will get either null or user email address.
Added: User email address could be undefined, that's why you need != null check (non-strict). It will be false if variable is undefined or null.

Dynamic field names in MongoDB using Mongoose

. Sample of collection Flights :
{
"Orig" : "AGP",
"Dest" : "CMN",
"Description_Flight" : "One-Stop-Narrow Type",
"Description_Flight_2" : "WESTERN EUROPE/WESTERN EUROPE",
"Mkt_Al" : "0B"
}
. Sample of collection Coeff :
{
"Regions" : "WESTERN EUROPE/WESTERN EUROPE",
"Non-Stop-Narrow Type" : 2.4109,
"Non-Stop-Supersonic" : 2.71828,
"One-Stop-Narrow Type" : 2.22554,
"One-Stop-Turbo" : 0.92312,
"One-Stop-Wide Type" : 11.24586,
"One-Stop Online-Turbo" : 0.07577
}
What I want ?
I Have my starting collection, Flights and for each document I want to put a score, a score which based on the Description_Flight_2 and Description_Flight.
Example :
For example, in my sample I have :
"Description_Flight" : "One-Stop-Narrow Type",
"Description_Flight_2" : "WESTERN EUROPE/WESTERN EUROPE",
So, I should go to the Coeff collection, and find the region :
"WESTERN EUROPE/WESTERN EUROPE"
and then take the appropriate value, here I should take this value in this line :
"One-Stop-Narrow Type" : 2.22554,
I have tried this :
mongoose.connect('mongodb://localhost/mydb');
var cSchema = new Schema({},{ strict: false, collection: 'flights' }),
dflights = mongoose.model("flights", cSchema);
var rSchema = new Schema({},{ strict: false, collection: 'coeff' }),
coeff = mongoose.model("coeff", rSchema);
mongoose.set('debug', false);
mongoose.connection.on("open", function (err) {
if (err) throw err;
dflights.find({}).lean().exec(function (err, flights) {
if (err) throw err;
flights.forEach(function(flight) {
var Flight_Description = "", score =0 ;
coeff.findOne({Regions : flight.Description_Flight_2}).lean().exec(function (err, coef) {
And here the important lines :
Flight_Description = flight.Description_Flight;
score = (coef != null ) ? coef.Flight_Description : "Missed data";
Here the last lines
if ( score != 0)
dflights.collection.update({_id:flight._id}, { $set : { score :score } } );
});
});
});
});
Please how can I achieve the above ?
The correct code should be:
score = (coef != null ) ? coef[Flight_Description] : "Missed data";

Categories

Resources