How to check if current Meteor.user()._id exists in "favoritedBy" array?
If true, print "Your favorite", if false, print "Not your favorite".
Document in MongoDB:
{
"_id" : "W5WwAZatorDEb6DNP",
"createdBy" : "aTmb64zNGSyeDYFJZ",
"favoritedBy" : [
"X594baqWYZiJqA3Qg",
"fgk234m2dkD229d12"
]
}
Say that Meteor.user()._id returns X594baqWYZiJqA3Qg.
How can I do a true/false check on this?
I tried the following:
isFavorite: function() {
var user = Meteor.user()._id;
return Posts.find({favoritedBy: user});
}
In the template:
{{#if isFavorite}}
Your favorite
{{else}}
Not your favorite
{{/if}}
But it don't seem to work, as it always return as "Your favorite", even if current Meteor user id is not in the array.
Any ideas?
you can use
isFavorite: function() {
var user = Meteor.user()._id;
return Posts.find({favoritedBy: user}).count() > 0 ? true : false;
}
count() will returns the count of documents that would match a find() query then check if its > 0 , and by using ternary operator, if yes it will return true if not it will return false
Related
I know how to ask a user for his or her user name by a popup with Vue-SweetAlert2.
<template>
<v-btn class="create-button" color="yellow" #click="alertDisplay">Create</v-btn>
<br/>
<p>Test result of createCustomer: {{ createdCustomer }}</p>
</div>
</template>
<script>
export default {
data() {
return {
createdCustomer: null
}
},
methods: {
alertDisplay() {
var customer = await this.$swal({
title: 'What is your Name?',
input: 'text',
inputPlaceholder: 'Enter your name here',
showCloseButton: true,
});
console.log(customer);
this.createdCustomer = customer;
}
}
}
</script>
With code like the one above, you can store whatever the user typed into createdCustomer, and it should be displayed on the screen after the user gives the input.
But what if I wanted to ask the user for multiple pieces of information?
For example, how do I ask for info like
"customerNumber" (also want to make sure that alphabets and numbers are combined)
"locale" (also want to make sure that the input is a collection of choices that the user chooses from, like drop down menu, rather than a text field where you can type in whatever you like)
"firstName" (also want to make sure that the name doesn't exceed 255 characters)
etc.
in a single popup?
I tried to set multiple input fields like below, but I got a warning "Unknown parameter", and this doesn't seem to be a valid way.
var customer = await this.$swal({
title: 'Fill in your personal data',
input1: 'text',
input2: 'text',
input3: 'text',
inputPlaceholder: 'Enter your name here',
showCloseButton: true,
});
And how do I check if the user has given a valid input (like the name is within 255 characters, both of alphabets and numbers are used etc)?
If I were using C or Java, I could imagine using if-statements like
if(length <= 255){
// proceed
} else {
// warn the user that the input is too long
}
somewhere in the code, but in this case I don't know how I can do a similar if-statement like thing within the popup...
[ADDITIONAL QUESTION]
Is it also possible to pass an object that consists of multiple smaller elements, like "address"?
"address": {
"street": "string",
"city": "string",
"country": "USA",
"region": "string",
"zipCode": "string"
}
As per the documentation :
Multiple inputs aren't supported, you can achieve them by using html
and preConfirm parameters. Inside the preConfirm() function you can
return (or, if async, resolve with) the custom result:
const {value: formValues} = await Swal.fire({
title: 'Multiple inputs',
html: '<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]
}
})
if (formValues) {
Swal.fire(JSON.stringify(formValues))
}
https://sweetalert2.github.io/
For validation you have to use the inputValidor prop like this :
const {value: ipAddress} = await Swal.fire({
title: 'Enter your IP address',
input: 'text',
inputValue: inputValue,
showCancelButton: true,
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}
}
})
if (ipAddress) {
Swal.fire(`Your IP address is ${ipAddress}`)
}
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.
I have added an array of objects to my user collection in my Meteor app, called contacts. It now looks like this:
{
"_id" : "p6c4cSTb3cHWaJqpG",
"createdAt" : ISODate("2016-05-11T11:30:11.820Z"),
"services" : {
.....
},
"username" : "admin",
"emails" : [
{
"address" : "email#email.com",
"verified" : true
}
],
"points" : 28,
"contacts" : [
{
"when" : ISODate("2016-06-02T12:22:53.747Z"),
"who" : "4YBufbE9PByJBkasy"
},
{
"when" : ISODate("2016-06-02T12:00:41.833Z"),
"who" : "EvF7DbFazmiuG86mD"
},
{
"when" : ISODate("2016-06-02T12:21:41.415Z"),
"who" : "MNFTSzjjzmYWgDvey"
}
]
}
I can display the contacts on my page just fine, but they are in the order that they appear in the collection. I would like to sort them by the date in the when field. Is this possible?
My helper method:
Template.contacts.helpers({
'cont': function(){
var user = Meteor.user();
return user;
}
});
and my Template:
<template name="contacts">
{{#each cont.contacts}}
<h1>{{who}}</h1>
{{/each}}
</template>
Akram Saouri was on the right track, I just needed to dig a little deeper. So I'll post the 100% working solution I came up with off that. The docs are your friend
Client.js:
Template.contacts.helpers({
'cont': function(){
var contacts = Meteor.user().contacts;
var result = contacts.sort(function (a,b) {
if (a.when > b.when){
return -1;
}
if (a.when < b.when){
return 1;
}
return 0;
});
return result;
}
});
Blaze Template:
<template name="contacts">
{{#each cont}}
<h1>{{who}}</h1>
{{/each}}
</template>
You can send the contacts array directly from the helpers and pre-sorted it like this :
Template.contacts.helpers({
'cont': function(){
var user = Meteor.user();
var contacts = user.contacts.sort({'when':'-1'})
return contacts;
}
});
In this way, you blaze 'll look much simpler :
<template name="contacts">
{{#each contacts}}
<h1>{{who}}</h1>
{{/each}}
</template>
So I have an array called domains which returns a variation of data, among which is a category spanding from 0-12.
It looks something like:
domains: {
0 {
available : true
category : 0
}
1 {
available : true
category : 1
}
2 {
available : true
category : 2
}
3 {
available : true
category : 3
}
4 {
available : true
category : 4
}
}
Then I have the following keys:
categoryLabels {
0 : Professional
1 : Government
2 : Finance
3 : Business
4 : Colors
}
Now what I would like to do is to display the matchin category with the matching categoryLabel
I have tried this but it doesnt seem to work:
for (key in this.categoryLabels) {
var item = {
name: key, // Push the key on the array
value: this.categoryLabels[key] // Push the key's value on the array
};
return this.categoryName;
console.log(this.categoryName.value);
}
Does anyone have a solution ?
I tweaked your sample data assuming you are having a valid Data .
view:
<div data-bind="foreach:dom.domains">
<p> available</p> : <b data-bind="text:available"></b>
<p> category </p> : <b data-bind="text:ctgry.categoryLabels[category]">
</div>
code:
var dom = {
'domains': [{
'available': true,'category': 0}, {'available': true, 'category': 1 },{'available': true,'category': 2 },{ 'available': true,'category': 3},{'available': true, 'category': 4
}]
};
var ctgry = {
'categoryLabels': { 0: 'Professional',1: 'Government', 2: 'Finance',3: 'Business',4: 'Colors',
}
}
ko.applyBindings({ //pass your json data here
dom,
ctgry
});
sample fiddle up for grabs
PS: Instead of passing json data directly to ko,however you can have your viewModel created and store it in observable & bind to view.
I am creating a dgrid based on a data source which has an address and two columns with Boolean values which identifies what type of address is in the record, either postal address or business address.
I would like to display a descriptive name for the Boolean values in another column (Address Type) based on the two Boolean columns. I am trying to use the dgrid formatter function however i am unable to get the desired results. Under is my code:
Javascript
function getAddressType(){
$.each(employeeAddressData, function(key, value){
if(key == "postalAddress"){
if(value == true || value == 'true'){
console.log('returning postal');
return 'Postal';
}
}else{
console.log('returning business');
return 'Business';
}
});
}
var Employer = [{id: 1, businessName:'John Doe and Sons Limited',phone:'123456',address:'123 Long Street', postalAddress:true, businessAddress:false},
{id: 1, businessName:'Alice and Bob Limited',phone:'78956', address:'56 Short Street', postalAddress:false, businessAddress:true}];
var employerGrid = new CustomGrid({
store: employerStore,
columns:{
id:{
label:"Id",
field:"id",
hidden:true
},
businessName:{
label:"Business",
field:"businessName",
},
phone:{
label:"Contact No.",
field:"phone",
},
address:{
label:"Address",
field:"address",
},
addressType:{
label:"Address Type",
formatter:getAddressType();
}
},
selectionMode:"none",
loadingMessage: "Loading data...",
noDataMessage: "No results found....",
allowSelectAll: true
}, "employerGrid");
I realized dgrid has a get function which i can use to access the datasource attributes. So formatter was not needed instead get was used. Under is my solution :
Javascript
},
addressType:{
label:"Address Type",
get: function(object){
if(object.postalAddress == true){
return 'Postal';
}else{
return 'Business';
}
}
}