Meteor useraccounts:core role empty - javascript

I'm trying to learn Meteor through a video tutorial to finish the code did not get the same result. Here is the code:
Meteor.startup(function(){
if(Meteor.users.find().count() < 1){
var users= [
{
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
}
];
_.each(users, function(user){
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile:{
name: user.name
}
});
if(user.roles.length > 0){
Roles.addUsersToRoles(id, user.roles);
}
});
}
});
It is assumed that Meteor.roles.find.().fetch () console should appear: Object name: 'admin' _id. 'whatever'; but my pops me empty [ ].
I'm using alanning: roles from atmospherejs
Thanks in advance.

Have you installed the accounts-ui and accounts-passwords packages? It might be related to that. I suggest you to install the meteortoys:allthings to check what is wrong with your DB.

Meteor.startup(function() {
if (Meteor.users.find().count() < 1) {
var users = {
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
};
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile: {
name: user.name
}
});
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles, 'defaultgroup');
}
});
}

Related

forEach looping for object in array [duplicate]

This question already has answers here:
Function with forEach returns undefined even with return statement
(5 answers)
Closed 2 years ago.
database = [
{
username: 'mutho',
password: 'muth',
},
{
username: 'pica',
password: '1234',
},
{
username: 'rudy',
password: '1235'
}
];
news = [
{
username: 'sarah',
timeline: 'Hellow',
},
{
username: 'ingrid',
timeline: 'hello world'
},
{
username: 'rudy',
timeline: 'secret',
}
];
function isvalid(user, pass) {
database.forEach(function (item, index) {
if (item.username === user && item.password === pass) {
return true;
}
return false;
});
}
function signIn(user, pass) {
if (isvalid(user, pass) === true) {
console.log(news);
}
else {
alert("Your Username and password wrong");
}
}
var userprompt = prompt("Input your username : ");
var passprompt = prompt("Input your password : ");
signIn(userprompt, passprompt)
I have some problem, I want to show news is the user and password are right in the database. but when I run this program, it always showing "Your Username and password wrong". what should I do?
thank you for the helping
You need Array#some and return the result of this method.
function isvalid(user, pass) {
return database.some(function(item, index) {
return item.username === user && item.password === pass;
});
}
function signIn(user, pass) {
if (isvalid(user, pass)) {
console.log(news);
} else {
alert("Your Username and password wrong");
}
}
var database = [{ username: 'mutho', password: 'muth' }, { username: 'pica', password: '1234' }, { username: 'rudy', password: '1235' }],
news = [{ username: 'sarah', timeline: 'Hellow' }, { username: 'ingrid', timeline: 'hello world' }, { username: 'rudy', timeline: 'secret' }],
userprompt = prompt("Input your username:"),
passprompt = prompt("Input your password:");
signIn(userprompt, passprompt);
Maybe you re looking for something like this:
function findValidUsers(user, pass) {
return database.filter(item => item.username === user && item.password === pass)
}
where findValidUsers will return a array of all users in your database array that have the same username and password.
e.g:
findValidUser('mutho','muth')
would return {username: 'mutho', password: 'muth'}
Your return true does NOT break your loop, it just ends your callback.
See this: Short circuit Array.forEach like calling break.
Or that: https://stackoverflow.com/a/6260865/3872061.
It might help you understand where your problem lies.
foreach doesn't return any value (or break and early return).
Use a standard for loop.
Example https://stackoverflow.com/a/35450142/3327009
Also, the way you have done it now it will just check your first object in the array (if you translate to a for loop)
You need something like this
var i
for (i=0; i<database.length;i++)
if(foobar)
return true
return false

How can I pass parameter correctly?

const root = {
user: (id) => {
console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id)))
return storage.select("users", id.id)
}
}
I want to call the arrow function in root.user but I think I can't pass the parameter correctly, so I tried this --> let user = root.user('101')
and on the console I got this -->
returning object undefined
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
{"firstName":"George","lastName":"Clooney","login":"gclooney"}
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
I wanted the user with the id 101 get returned and got instead all of the users returned.
Why are you doing id.id but passing a string? You either pass an object with an id prop (root.user({ id: '101' })) or replace id.id with simply id.
Also, it looks like the id fields in your user objects are of type number, while you are passing a string, so depending on the logic inside storage.select you might have to change that.
Passing a number id:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id)
},
};
const root = {
user: (id) => {
console.log(`ID = ${ id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', id)[0] || null;
},
};
const user = root.user('101');
console.log(user);
Passing an object with an id prop of type number:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id);
},
};
const root = {
user: (query) => {
console.log(`ID = ${ query.id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', query.id)[0] || null;
},
};
const user = root.user({ id: '101' });
console.log(user);

Edit operation failing in Node

This is my code:
router.post('/update-posting', (req, res, next) => {
Account.findById(req.user._id)
.then(doc => {
var type = [];
if (req.body.full !== undefined) {
type.push('full');
}
if (req.body.part !== undefined) {
type.push('part');
}
if (req.body.seasonal !== undefined) {
type.push('seasonal');
}
if (req.body.temporary !== undefined) {
type.push('temp');
}
var title = req.body.title;
var salary = req.body.salary;
var timeline = req.body.timeline;
var experience = req.body.experience;
var description = req.body.description;
var duties = req.body.duties;
doc.postings[req.body._id] = {
_id: req.body._id,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
};
doc.save(r=>console.log(r));
})
.then(() => res.redirect('/employer/booth-edit'))
.catch(e => console.log(e))
});
And here's the model:
var mongoose = require('mongoose');
var plm = require('passport-local-mongoose');
var accountSchema = new mongoose.Schema({
// username (comes with passport): email; -> just for reference.
accType: String,
fullName: String,
displayName: String,
companyName: String,
contactPersonFullName: String,
companyWebsite: String,
city: String,
province: String,
postalCode: String,
phoneNumber: String,
hiringRegion: [], // TODO
description: String,
logo: [],
workingWithEOESC: Boolean,
industry: String,
phone: String,
ageGroup: String,
education: String,
lookingForWork: String,
employmentStatus: String,
resume: [],
mainWorkExp: String,
boothVisits: Number,
postings: []
});
accountSchema.plugin(plm);
module.exports = mongoose.model('account', accountSchema);
What I'm doing is trying to update an object in the postings array. Now here's the weird part. When I console log the result before doc.save() I get the updated version... And when I console log the response from doc.save() I get null... I'm sure that's a small bug but I cannot see it anywhere.
All fields are coming from the req.body object correctly.
Here are the logs.
Original object:
{ _id: 0,
title: 'Web developer',
type: [ 'full', 'seasonal' ],
salary: '14$',
timeline: '3 months',
description: 'tada',
duties: 'tada',
experience: '5 years' }
Updated object:
{ _id: '0',
title: 'Car mechanic',
type: [ 'part', 'temp' ],
salary: '50$',
timeline: '2 weeks',
description: 'desc',
duties: 'resp',
experience: '4 years' }
doc.save() response:
null
What's more interesting, this is the code I'm using for "creating" a job posting. It's almost the same code, and it works perfectly well:
router.route('/add-posting')
.get((req, res, next) => {
res.render('users/employer/add-posting', {
title: 'Employer Booth - Add Job Posting',
user: req.user
});
})
.post((req, res, next) => {
// Determining type of work.
var type = [];
if (req.body.full !== undefined) {
type.push('full');
}
if (req.body.part !== undefined) {
type.push('part');
}
if (req.body.seasonal !== undefined) {
type.push('seasonal');
}
if (req.body.temporary !== undefined) {
type.push('temp');
}
var title = req.body.title;
var salary = req.body.salary;
var timeline = req.body.timeline;
var experience = req.body.experience;
var description = req.body.description;
var duties = req.body.duties;
Account.findById(req.user._id)
.then(doc => {
doc.postings.push({
_id: doc.postings.length,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
});
doc.save();
})
.then(() => res.redirect('/employer/booth-edit'))
.catch(e => console.log(e));
});
They way you're doing it may work. But mongo has already provided you with update or findOneAndupdate methods. I'd suggest you to use them.
Your query would be easy to understand and debug when needed.
Try something like
db.collection.update({_id: .user._id},{$push :{postings: yourObject}})
I just remembered I had this issue before. Turns out that to update an array we need to do this:
doc.postings.set(req.body._id, {
_id: req.body._id,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
});
I remember reading an issue on that. Will add the link if I find it again.
We need to use the .set method instead of the = operator.

Find valid object from array of objects

I have the following array in my javascript code:
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
From this collection I want to retrieve user by email. So for example I will write:
my_function("test#user.com") it will return this one user. How can I do this?
You can use Array#find function. Pass a predicate into the function, which will return the first matched item based on that predicate.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findByEmail(email) {
return users.find(x => x.email === email);
}
console.log(findByEmail('test#user.com'));
That's what the .find() method is for.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
];
console.log(users.find(u => u.email == 'test#user.com'));
So .find() is called on the array, and receives a callback function. The callback will be invoked for each item in the array, for which you return the result of comparing the .email property to the email you're looking for.
As soon as your callback returns a true (or truthy) result, the iteration halts, and returns that object from .find(). If no is found, .find() returns undefined.
Note that this uses arrow function syntax. If you prefer, you can use traditional functions.
console.log(users.find(function(u) { return u.email == 'test#user.com' }));
There's always the good old fashioned for-loop:
const users = [{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findUserByEmail(userList, desiredEmailAddress) {
for (let i = 0; i < userList.length; i++) {
var user = userList[i];
if (user.email === desiredEmailAddress) {
return user;
}
}
return null;
}
var desiredUser = findUserByEmail(users, 'second#user.com');
if (desiredUser) {
console.log('User found by email:\n');
console.log(desiredUser);
} else {
console.log('No user found with searched email address');
}

Using ngstorage for persistent data

I know that there are solutions to how to use ngstorage in our applications to have persistent data available even after refresh. I tried implementing it for the first time in my form today. But unable to figure out where I am going wrong. Can someone please let me know where I am going wrong? Also, I am looking to have the persistent functionality on adding and deleting the data.
angular.module('myApp', ['ngStorage'])
.controller('AppController', ['$scope', '$localStorage',
'$sessionStorage',
function($scope,$localStorage,$sessionStorage) {
var self = this;
self.$storage = $localStorage;
self.user = {
id: null,
username: '',
address: '',
email: ''
};
self.id = 4;
self.users = [{
id: 1,
email: 'sam#tarly.com',
firstname: 'Sam',
lastname: 'Tarly',
telephone: 1234567890,
address: 'NY',
}, {
id: 2,
email: 'jon#snow.com',
firstname: 'Jon',
lastname: 'Snow',
telephone: 9876543210,
address: 'The Wall',
}, {
id: 3,
email: 'dany#targaryen.com',
firstname: 'Dany',
lastname: 'Targaryen',
telephone: 1234987650,
address: 'NEBRASKA'
}];
self.submit = function() {
if (self.user.id === null) {
self.user.id = self.id++;
alert('Added New User', self.user);
self.users.push(self.user);
$localStorage.users = self.users;
} else {
for (var i = 0; i < self.users.length; i++) {
if (self.users[i].id === self.user.id) {
self.users[i] = self.user;
break;
}
}
alert('User updated with id ', self.user.id);
}
self.reset();
};
self.edit = function(id) {
alert('id to be edited', id);
for (var i = 0; i < self.users.length; i++) {
if (self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
};
self.remove = function(id) {
alert('id to be deleted', id);
for (var i = 0; i < self.users.length; i++) {
if (self.users[i].id === id) {
self.users.splice(i, 1);
$localStorage.users = self.users;
if (self.user.id === id) { //It is shown in form, reset it.
self.reset();
}
break;
}
}
};
self.reset = function() {
self.user = {
id: null,
username: '',
address: '',
email: ''
};
$scope.myForm.$setPristine(); //reset Form
};
}
]);
Plnkr Link
From my understanding, for you the issue is the value not shown in table after adding the data and refreshing the page. The problem is you are initially loading the data with static array value. The data is infact added to storage. You just have to call the initial loading from $localStorage. Just change the self.users = [{..}] to self.users = $localStorage.users. I have updated the plunkr. Please take a look at it.
Plunkr

Categories

Resources