Iterating a multi-dimensional object with es6 - javascript

Are there any methods on how can I iterate between object keys
var dataSubmit = {
email : {
value : email,
rules : 'required email'
},
password : {
value : password,
rules : 'required,min:6'
}
};
I was hoping I can access it like
each (data in dataSubmit) {
console.log(data.value);
console.log(data.rules);
}
and get
email: {value : email, rules : 'required, email'};
so I can
iterator {
func(email: {value : email, rules : 'required, email'})
}
I need to keep the object as whole

for(const data of Object.values(dataSubmit))
console.log(data.value, data.rules);
Just use for..of on the objects values.

You're almost there, use the for...in statement for that - replace each with for.
var dataSubmit = {
email : {
value : 'email',
rules : 'required email'
},
password : {
value : 'password',
rules : 'required,min:6'
}
};
for (let key in dataSubmit) {
console.log(dataSubmit[key]);
}
Alternatively use the for...of statement with Object.values(dataSubmit) which returns an array of values
var dataSubmit = {
email : {
value : 'email',
rules : 'required email'
},
password : {
value : 'password',
rules : 'required,min:6'
}
};
for (let data of Object.values(dataSubmit)) {
console.log(data);
}

You could use forEach loop on Object.values.
var dataSubmit = {email: {value: "email",rules: 'required email'},password: {value: "password",rules: 'required,min:6'}};
Object.values(dataSubmit).forEach(o => {
console.log(o.value);
console.log(o.rules)
})

Related

Express-validator test item's array independantly

I'm trying to add a validation chain on an object which contain an array;
this array contain objects that have to be tested differently according to one of the field of the object,
here is an example :
{
"title" : "my title",
"sections" : [
{
"type": "A",
"optionsA" : {...}
},
{
"type": "B",
"optionsB" : {...}
},
{
"type": "A",
"optionsA" : {...}
},
{
"type": "C",
"optionsC" : {...}
},
]
}
is there a way to achieve this ? i tried to use OneOf() with specific test for each section but with no success
while this solution is a bit more work I think it's the most straightforward and maintainable.
Download the Validator & Is-emptypackages
Using this package you can validate and JSON object with a lot of control. So I use it like this to validate my req.body
const Validator = require('validator');
const isEmpty = require('is-empty');
module.exports = function validateRegiterInput(data) {
let errors = {};
//Convert empty fields to a empty string so we can use validator functions
data.firstName = !isEmpty(data.firstName) ? data.firstName : "";
data.lastName = !isEmpty(data.lastName) ? data.lastName : "";
data.email = !isEmpty(data.email) ? data.email : "";
data.password = !isEmpty(data.password) ? data.password : "";
//school, schoolname? tbd
//Name check
if (Validator.isEmpty(data.firstName)) {
errors.firstName = "First name is required!"
}
if (Validator.isEmpty(data.lastName)) {
errors.lastName = "Last name is required!"
}
//Email check
if (Validator.isEmpty(data.email)) {
errors.email = "Email field is required!";
} else if (!Validator.isEmail(data.email)) {
errors.email = "Email is invalid!";
}
//Password check
if (Validator.isEmpty(data.password)) {
errors.password = "Password field is required!";
}
if (!Validator.isLength(data.password, { min: 6, max: 30 })) {
errors.password = "Password must be at least 6 characters!";
}
return {
errors,
isValid: isEmpty(errors)
};
};
So what happens is, I call this function with my data and im able to nest into arrays or objects just using the dot notation.
In the main file, I have this
const { errors, isValid } = validateRegisterInput(req.body);
If there were any errors then they'll be in the errors object. and is valid will be false. Otherwise, if it's empty the is valid is true and you're good to go. I hope this helped. If you need more clarification I'm here to help

Sequelize ORM - Error: not returning database values

I'm try to return a password from database to another javascript file. The function will retrieve the data correctly. But when I return the value to another function, it will be changed to undefined. I want to return a password from model.js to controller.js.
code :
model.js
const Sequelize = require('sequelize'); //import sequelize orm
// connect with psql db
var connection = new Sequelize('emd','postgres','test',{
dialect : 'postgres'
});
//create a table;
var student = connection.define('student',{
name : {
type : Sequelize.STRING,
allowNull : false},
email : {
type: Sequelize.STRING,
unique : true,
allowNull : false},
password : {
type : Sequelize.STRING,
allowNull : false },
mobile : {
type: Sequelize.BIGINT(11),
unique : true,
allowNull : false }
});
var methods = {};
methods.signup = function(u_name,u_email,u_password,u_mobile){
connection.sync().then(function(){
student.create({
name : u_name,
email : u_email,
password : u_email,
mobile : u_mobile
});
});
}
methods.login = function(email_id){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
return results.dataValues.password;
});
});
}
exports.fun = methods;
code: Controller.js
var model = require('./model.js')
var methods={}
methods.login = function(email,password){
let res = model.fun.login(email)
console.log(res);
if(password===res){
console.log("success");
}
else {
console.log("failure");
}
}
exports.cont = methods
To add on to #Sagar Jojoriya,
Change your model.js like this
methods.login = function(email_id, callbackFun){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
console.log("debug pass => ", results.dataValues.password);
callbackFun(results.dataValues.password);
});
});
}
And in your controller.js
methods.login = function(email,password){
model.fun.login(email, function(resPassword) {
if(password === resPassword){
console.log("success");
} else {
console.log("failure");
}
})
}
It's because the function model.fun.login is asynchronous so before getting response from this function, it'll move to the next statement, which returns undefined.
methods.login = function(email,password){
model.fun.login(email, function(resPassword) {
if(password === resPassword){
console.log("success");
}
else {
console.log("failure");
}
})
}
You can return the Promise and handle it in then block inside controller.
reutrn student.findOne({where : {email : email_id }} ));
This will return the promise. In the controller, you can call the method as
model.fun.login(email).then(function(result){
console.log(JSON.stringfy(result));
});

Update Data from Within a Loop

I am trying to get my nodejs controller to update the rate in the currency table.
Everything works fine in S3T / RoboMongo, but for some reason it just wont fire the update inside the nodejs controller.
Here is my currency table
{
"_id" : "USD",
"index" : NumberInt(6),
"name" : "Dollar",
"currency" : "USD",
"symbol" : "$",
"active" : true,
"default" : false,
"rate" : 0
}
{
"_id" : "EUR",
"index" : NumberInt(2),
"name" : "Euro",
"currency" : "EUR",
"symbol" : "€",
"active" : true,
"default" : false,
"rate" : 0
}
I tried both of these, works fine in S3T but not inside nodejs:
db.currency.update (
{ _id : "EUR" },
{ $set: { rate : 123 }},
{ upsert: true }
)
db.currency.updateOne (
{ _id : "EUR" },
{ $set: { rate : 123 }},
{ upsert: true }
)
Here is my nodejs code:
var mongoose = require('mongoose');
var currencyModel = require('../models/currencyModel');
var currencyTable = mongoose.model('currencyModel');
var updateRates = () => {
return new Promise((resolve, reject) => {
for (var key in data.quotes) {
var currencyID = key.substring(3);
var newRate = (data.quotes[key] * THBUSD).toFixed(5);
console.log("currencyID: " + currencyID)
console.log("newRate: " + newRate)
currencyTable.update (
{ _id: currencyID },
{ $set: { rate : newRate }},
{ upsert: true }
),function (err, data) {
if (err) {
reject(new Error('updateRates: ' + err));
};
};
};
resolve();
})};
And here is my currencyModel (which is where I think the problem is?!?)
// Currency Model
// This model is the structure containing data from the Currency table
//
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var currencySchema = new Schema({
_id: String, // Unique Currency code
index: Number, // Indes for sorting
name: String, // Currency name
symbol: String, // Currency symbol
active: Boolean, // Active True False
rate: Number // Exchange rate (multiply with THB price)
});
module.exports = mongoose.model('currencyModel', currencySchema, 'currency');
I cannot see why it wont fire the currencyTable.update from inside nodejs.
I turned debug on in mongoose, and I see all other mongodb operations in the console like Mongoose: price.findOne({ _id: 'ATL-D406' }, { fields: {} }) etc.. but I do not see this currency.update in the console, which is why I dont think its fired off to mongodb - and I cannot see the reason.
You have a "loop" that completes execution before the inner callbacks fire. Instead just use Promises all the way through and call Promise.all() to collect all the iterated Promises and resolve them:
var updaterates = () => {
return Promise.all(
Object.keys(data.quotes).map(k => {
return currencyTable.update(
{ _id: k.substring(0,3) },
{ $set: { rate : (data.quotes[k] * THBUSD).toFixed(5) }},
{ upsert: true }
).exec()
});
)
};
The returned response of Promise.all() is an array of the response objects from the updates. Also note that this is a "fast fail" operation and calls will be made in parallel.
Object.keys() returns an "array of the key names" in the specified object. .map() iterates those keys and returns an "array" of the return value for the iterator.
We use the k as the "key name" to access the wanted key from data.quotes and use the values to perform each .update() with .exec() to return a "real" Promise. The iterator returns an "array" Promise which becomes the argument to Promise.all().

search in array filed of mongodb by mongoos in query

I have a collection Events in my Mongodb and it has an array filed called for_who.
This field is for checking if a user id is in this array, so this user can see this Event. I want to get the Events that for_who field contains user_id.
This is my current query:
Events.find(
{ for_who: { "$in" : [user_id]} }
).lean().exec(function(err , obj) { ... });
my schema:
var eventSchema = new mongoose.Schema({
id : { type: Number , required: true , unique: true } ,
title : { type: String , required: true } ,
created_at : { type: String , required: true } ,
for_who : { type: Array }
});
var Events = mongoose.model('Events', eventSchema);
Events.find().then((events) => {
var userData = events.find((v) => {
return v.for_who === user_id
})
if(userData){
//user was found
}
})
i think this cloud work

Mongodb - Search by id and embedded array value

Im trying to write a function that will search for an object by ID and whether or not a value is contained in an embedded array within the object.
{
"_id" : ObjectId("569bea91c0e1fee4063527ac"),
"user" : ObjectId("568c65174fee132c36e199dd"),
"votes" : 9,
"image" : "./modules/deals/client/img/uploads/1546f914dba7e1732ea853cd70d79148.jpg",
"price" : "12.95",
"retailer" : "argos.co.uk",
"voters" : [{
"user" : ObjectId("568c65174fee132c36e199dd"),
},
{
"user" : ObjectId("568c65174fee132c36e199dd"),
},
{
"user" : ObjectId("568c65174fee132c36e199dd"),
}]
I would like to search by the _id and the voters.user.
I believe i need to finish this function correctly
exports.dealByIdAndVoter = function(req, res) {
Deal.count({
$where: function () {
}
},
function(err, dealByIdAndVoter) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log(dealByIdAndVoter);
var data = {};
data.count = dealByIdAndVoter;
res.json(data);
}
});
};
If you do not need to use the $where function, you can construct the query with the $or operator in this manner:
Deal
.find({
$or: [
// Match by _id
{ _id: req.id },
// Match by any user in the 'voters' array with a matching 'user' field.
{ 'voters.$.user': req.id }
]
})
.count(function(err, count) {
// Handle error here
res.json(count);
});

Categories

Resources