Get data from Firebase db, comes back without key value - json

I am retrieving data from Firebase db using REST call. So i have a data looking like this
user
{
123456:
{
Email: "test#hotmail.com",
Password: "John Doe"
}
654321:
{
Email: "test2#hotmail.com",
Password: "Jane Doe"
}
}
The query I used is
firebaseurl/user.json?orderBy="Email"&equalTo="test#hotmail.com"
Is it possible if I query without the key value 123456 being retrieve? Because whenever I try to use the data, for instance console.log(user.Email), I am getting undefined. But when I do it likeconsole.log(user[123456].Email) then will I get the result I desire.
May I know if there's a way to do it? Or a way to access to the child element without user[keyvalue].

As it is expected only single record in return you can use:
const user = obj[Object.keys(rslt)[0]]
Or you can loop over the keys
const usersArr = Object.keys(rslt).map(usr => {
... manipulate usr
return usr
})

Related

How to store n number of inputs into an array using mysql in express.js

Hi I a beginner to the web development
I wanted to accept n number of the instance(n is inputted by the user) from the user and then store those values in an array-like structure so that my frontend can have access to it. Can this be done using mysql ?. I was reading StackOverflow posts that mentioned that it is not a good idea to use MySQL for this. However I am already kind of deep into my project so I want to clarify this.
Is this feasible using MySQL?
I guess you want to store something like object or array of something
let's say that in your front end there is a form with input and button
where the input is Add More Columns and the input is value so in your backend you will get an array of objects like
[
{ question: '1', answer: 'Answer1' },
{ question: '2', answer: 'Answer2' },
{ question: '3', answer: 'Answer3' },
{ question: '4', answer: 'Answer4' }
]
you can make a table
id | userId | payload
where id is generated by SQL
userId that you injected in the token (or something else to relate the user with his payloads)
and payload that contains the information that you need to store
const saveUserPayLoads = async (req, res) => {
const { payloads } = req.body;
const { id } = req.user
const data = []
for(payload of payloads) data.push(DBModule.create({ payload: JSON.stringify(payload), userId: id }))
return res.status(201).json({
message: 'Done',
success: true,
data
})
}

email verification from database using express js node js and angular 6 with mysql database

i am creating a user, with 'email' field so i want to verify whether that email is already exist or not, if exists error must display. i have my code in express js, node js, angular 6 and mysql database and below is the code to create new user
exports.create = (req, res) => {
// Save to MySQL database
let customer = req.body;
Customer.create(customer).then(result => {
// Send created customer to client
res.json(result);
});
};
where should i use if statement in above code
Thanks in advance
I'm thinking the simplest way of solving your problem is making the email column in the database unique. If you try to insert a new user with an already existing email the query will fail.
Another solution would be that you first do a query that looks in the database if an already existing user has the email (from req.body.email). But that would require having two different SQL queries, which I personally would not prefer.
i think you are using Sequelize ORM.
You can do like this
Customer.findOrCreate({
where: {
email: req.body.email,
},
// other datas needs to inserted
defaults: {
name: req.body.name,
username: req.body.username,
},
}).spread((data, created) => {
if (created) {
// your logics
} else {
res.status(400).send(`${req.body.email} already exists.`);
}
});

Hooks not triggering when inserting raw queries via sequelize.query()

I have the following Employee model for a MySQL database:
var bcrypt = require('bcrypt');
module.exports = (sequelize, DataTypes) => {
const Employee = sequelize.define(
"Employee",
{
username: DataTypes.STRING,
password: DataTypes.STRING,
}, {}
);
return Employee;
};
Seeding the database is done by reading a .sql file containing 10,000+ employees via raw queries:
sequelize.query(mySeedingSqlFileHere);
The problem is that the passwords in the SQL file are plain text and I'd like to use bcrypt to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the Employee model, like so:
hooks: {
beforeBulkCreate: (employees, options) => {
for (employee in employees) {
if (employee.password) {
employee.password = await bcrypt.hash(employee.password, 10);
}
}
}
}
This isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook
Your hooks won't be called until you use model's function for DB operation , so if you are running raw query , hooks will never be fired,
Reason : You can write anything inside your raw query , select/insert/update/delete anything , how does sequelize.js know that
it has to fire the hooks. This is only possible when you use methods
like
Model.create();
Model.bulkCreate();
Model.update();
Model.destroy;
And as per DOC raw query doesn't have hooks option to add.
And for MODEL queries you can check that it has option to
enable/disable hook.

How do you insert / find rows related by foreign keys from different tables using Sequelize?

I think I've done enough research on this subject and I've only got a headache.
Here is what I have done and understood: I have restructured my MySQL database so that I will keep my user's data in different tables, I am using foreign keys. Until now I only concluded that foreign keys are only used for consistency and control and they do not automatize or do anything else (for example, to insert data about the same user in two tables I need to use two separate insert statements and the foreign key will not help to make this different or automatic in some way).
Fine. Here is what I want to do: I want to use Sequelize to insert, update and retrieve data altogether from all the related tables at once and I have absolutely no idea on how to do that. For example, if a user registers, I want to be able to insert the data in the table "A" containing some user information and in the same task insert in the table B some other data (like the user's settings in the dedicated table or whatever). Same with retrievals, I want to be able to get an object (or array) with all the related data from different tables fitting in the criteria I want to find by.
Sequelize documentation covers the things in a way that every thing depends on the previous one, and Sequelize is pretty bloated with a lot of stuff I do not need. I do not want to use .sync(). I do not want to use migrations. I have the structure of my database created already and I want Sequelize to attach to it.
Is it possible insert and retrieve several rows related at the same time and getting / using a single Sequelize command / object? How?
Again, by "related data" I mean data "linked" by sharing the same foreign key.
Is it possible insert and retrieve several rows related at the same
time and getting / using a single Sequelize command / object? How?
Yes. What you need is eager loading.
Look at the following example
const User = sequelize.define('user', {
username: Sequelize.STRING,
});
const Address = sequelize.define('add', {
address: Sequelize.STRING,
});
const Designation = sequelize.define('designation', {
designation: Sequelize.STRING,
});
User.hasOne(Address);
User.hasMany(Designation);
sequelize.sync({ force: true })
.then(() => User.create({
username: 'test123',
add: {
address: 'this is dummy address'
},
designations: [
{ designation: 'designation1' },
{ designation: 'designation2' },
],
}, { include: [Address, Designation] }))
.then(user => {
User.findAll({
include: [Address, Designation],
}).then((result) => {
console.log(result);
});
});
In console.log, you will get all the data with all its associated models that you want to include in the query

Sequelize.js Node.js: How to Pass Already Created Object to Create Many-to-Many relationship?

From this post: Node.js / Sequelize.js / Express.js - How to insert into many-to-many association? (sync/async?)
The answer show only when you create Individual and Email, however, I want to create an Individual with an already created email.
Original answer to correctly create Individual and Email after one another:
models.Individual.create({
name: "Test"
}).then(function(createdIndividual) { // note the argument
models.Email.create({
address: "test#gmail.com"
}).then(function(createdEmail) { // note the argument
createdIndividual.addEmail(createdEmail)
.then(function(addedEmail) { // note th-- well you get the idea :)
console.log("Success");
});
})
});
To create an individual with an already created email, I modified into this:
models.Individual.create({
name: "Test"
}).then(function(createdIndividual) { // note the argument
//This email id exists in the Email table.
var email = {
id: 1
}
createdIndividual.addEmail(email)
.then(function(addedEmail) {
console.log("Success");
});
});
Then I got this error:
Unhandled rejection TypeError: val.replace is not a function
at Object.SqlString.escape (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/sql-string.js:63:15)
at Object.QueryGenerator.escape (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:977:22)
at /Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2203:23
at Array.map (native)
at Object.QueryGenerator.whereItemQuery (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2202:49)
at /Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1903:25
at /Users/Roller/Working/Web/ponds_web/node_modules/sequelize/node_modules/lodash/lodash.js:4389:15
at baseForOwn (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/node_modules/lodash/lodash.js:2652:24)
at Function.forOwn (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/node_modules/lodash/lodash.js:12254:24)
at Object.QueryGenerator.whereItemsQuery (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1902:9)
at Object.QueryGenerator.getWhereConditions (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2337:19)
at Object.QueryGenerator.selectQuery (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1451:28)
at QueryInterface.select (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/query-interface.js:669:25)
at .<anonymous> (/Users/Roller/Working/Web/ponds_web/node_modules/sequelize/lib/model.js:1390:32)
at tryCatcher (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/Roller/Working/Web/ponds_web/node_modules/bluebird/js/release/promise.js:504:31)
I think this error because my email object is not a Sequelize object.
Questions in mind:
Should we convert the email object into a Sequalize object by query from Email models? Will it work?
What's the better way to convert that object into Sequalize, as clean code and performance are concerned?
What if I have multiple emails to be added into Individual_Email when creating a new Product? Like more than 1 email ids.
Please help to advice. Thanks.
You are correct, the problem is that email is not a sequelize object. It would work if you retrieve it from database before adding it. On the other hand sequelize allows you to set childs by id. So you can do something like this:
models.Individual.create({
name: "Test"
}).then(function(createdIndividual) {
createdIndividual.setEmails([emailIds]) //emails id array
.then(function() {
console.log("Success");
});
});