node.js passport user schema set it manualy - mysql

first sorry for my english ;)
second my question :
describtion :
I have :
var mongoose = require('mongoose');
// define the schema for our user model
var userSchema = mongoose.Schema({
facebook : {
id : String,
token : String,
email : String,
name : String
}
});
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
to use it with passport on a node.js .
...
var User = require('../app/models/user');
i dont connect to mongodb , since i use mysql to store my sessions .
the only stuff i dont understand is the _id value , comes it from passport , or sessions ?
question :
what i have todo to get a user model (object) so it is working together with passport/session ? or are there some method i need anyway , so it is better to get the user model from mongoose ?
sincerley rakondark

The id (known as the ObjectId) is generated and set by MongoDB for each documents.
I believe it auto-increments while using MySQL for passport.

Related

Is there a way to fetch data in database from a Ruby-on-Rails models

I have a rails app running alongside with a rails API, there is a constant value for DAYS_LIMIT in config/initializers/constants.rb
DAYS_LIMIT = 40
DEFAULT_PRICE = 1.29
but now in the app i added an input field so that the user decide his DAYS_LIMIT.
So i want to fetch that value from the database from inside the API models.
I have placed breakpoints and can see that inside the API controller, the data is transfered from the app but not to the models.
edited as a question requested , it's a React-on-Rails app , here is the code where the new input field is save to the database (i have removed the other fields so the question look shorter)
export const saveChannel = (files) => {
return async (dispatch, getState) => {
const { channel } = getState();
const {rss_podcast_days} = channel;
const { image } = files;
const save = id ? updateChannel : createChannel;
const sub_required = subscription_required !== undefined ? subscription_required : false;
const formData = new FormData();
formData.append('channel[rss_podcast_days]', rss_podcast_days || '');
if (Object.keys(image).length) {
formData.append('channel[image]', image);
}
const channelId = await dispatch(save(formData, id));
dispatch(fetchChannel(id));
return id;
};
};
from the app controller
podcast_list = RestClient.get("#{ENV['URL_API']}/api/#{#channel.id.as_json}/podcast/list")
#podcasts = JSON.parse(podcast_list.body)
#podcasts = #podcasts.sort.reverse.to_h
this is from the API controller witch the data is transfered from the app
def index
podcasts = #channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in])
render json: Podcasts::Normalizer.normalize(podcasts, #channel.station.default_podcast_price)
end
and here from the API model that i want to fetch data instead of the constants.
scope :by_days_limit, -> {with_tags.more_recent_than(Date.today - DAYS_LIMIT.days).ordered}
it should take today date minus the value (DAYS_LIMIT) from user input, but for now i get undefined local variable or method if i try to fetch directly
Bro if your class has constant like DAYS_LIMIT you can access it using that class itself for example,
class Demo
DAYS_LIMIT = 5
end
you can access that constant by Demo.DAYS_LIMIT in controller or else wherever you need it.
good luck!
ok , so i finally got it, i don't know if i should delete this thread or just tell how i did it. If it's inapropriate just tell me and i will delete this entire thread.
So here is how i did it, in the API controller i had to add my fetch so that the arguments (list) knows what i am talking about. #channel.days_limit
def index
podcasts = #channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in], #channel.days_limit)
render json: Podcasts::Normalizer.normalize(podcasts, #channel.station.default_podcast_price)
end
then in the def list of the models, i added days_limit has argument
def list(page = nil, nb_items_per_page = 40, ordered_in = 'desc', days_limit)
ordered_in = ordered_in.in?(['asc', 'desc']) ? ordered_in : 'desc'
page.blank? ? by_days_limit(days_limit) : by_page(page, nb_items_per_page, ordered_in)
end
and finally in the scope of the models, i pass in the new argument
scope :by_days_limit, -> (days_limit) {with_tags.more_recent_than(Date.today - days_limit.days).ordered}
Now the user input from the app is passing to the models via the controller.

Multiple tables with node mysql-model?

I'm working on a project where I use mysql-model and I don't really understand how models work when we have multiple tables.
I have some code on my model user.js:
var mysqlcon = require('../models/db_connexion');
var User_model = mysqlcon.extend({
tableName: "users"
});
var log_user = new User_model();
Some code ...
Then a function to find the user's role:
module.exports.findUserRole = function(userId,callback){
let findUserRoleId = "SELECT role_id FROM users WHERE id = "+userId;
log_user.query(findUserRoleId,function(err,rows,fields){
let role_id = rows[0].role_id;
let findRolesInfo = "SELECT role_name,role_power FROM roles WHERE role_id = " + role_id;
log_user.query(findRolesInfo,callback)
})
And when I call this function, it returns me what I want, but I don't understand why.
My User_model isn't normally using only the table "users" ? So why can I also access to the table "roles" ?
I've searched on the npm documentation and googled it, but didn't found anything, or I missed it.
Thanks for your explanation.
And sorry if I missed something with the presentation, that's my first post.

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.

Node js mysql wrapper error - Object #<Object> has no method 'table'

I am trying a nodejs mysql wrapper which I got from here.Everything is working including the setup and connection. But when I try saving a piece of data into the table, I get the error Object #<Object> has no method 'table'. When I just console the db object,I get the object, no error.
Can someone tell what I miss here ?
my global.js
//connect to mysql
var mysql = require('mysql');
var connection = mysql.createConnection({host : 'xxx.xxx.xxx.xxx', user : 'xxxx', password : 'xxxx', database : 'xxxx' });
connection.connect();
var wrapper = require('node-mysql-wrapper');
var db = wrapper.wrap(connection);
exports.db = db;
my app.js
var db = require('./global.js');
db.table('my_table').save( my_data_object );
The problem is that you're exporting a separate property instead of exporting directly. So either change exports.db = db to module.exports = db or change var db = require('./global.js') to var db = require('./global.js').db.
Additionally, you are referencing global.js instead of config.js as you show in your question, so depending on whether or not that is a typo, that could be another issue.

Database update issue using node-orm2 for mysql backend

Problem:
I am working on an Android app which interacts with nodejs REST server using node orm for mysql backend. On my server, I have a functionality of authenticating users based on email verification. Once verification is successful, node orm fetches the user object, changes the verified column value and saves it back.
But, the change is not reflecting in the db after execution. Only if we run the same code another time, it is reflecting in the database
Code
exports.activateEmail = function(email, callback) {
log.info('In verifyEmailDao.js, activateEmail module');
var db = connectionObj.getConnection();
var Candidate = db.models.jobseeker_id;
Candidate.find({email : email}, function(err,candidate){
if(err){
log.info('cannot find account with email to activate', email);
callback(false, null);
}
else {
candidate[0].verified = true;
log.info('candidate email now activated.! status is', candidate[0].verified);
candidate[0].save(function(error){
log.info('Email verified any errors?', error);
callback(true, candidate[0].id);
});
}
});
}
Edit 1:
jobseeker_id.js (node-orm model)
var orm = require('orm');
module.exports = function(db){
console.log('coming inside candidateId.js');
var JobSeekerId = db.define('jobseeker_id', {
id : {type:'serial' , key:true},
first_name : String,
last_name : String,
email : String,
password : String,
verified : Boolean
},{
validations : {
email : orm.enforce.unique("Already registered")
}
});
}
Server log:
{"name":"test-app" "msg":"In verifyEmailDao.js, activateEmail module"}
{"name":"test-app","msg":"candidate email now activated.! status is true"}
{"name":"test-app","msg":"Email verified any errors? null"}
{"name":"test-app","msg":"Email sucessfully activated. Now deleting the entry from verify email link table for candidate id 30}
{"name":"test-app","msg":"In verifyEmailDao.js, deleteRandomLink module"}
{"name":"test-app","msg":"error is---> null"}
{"name":"test-app","msg":"Entry deleted from verify email table as email is activated"}
There will no be no changes in the log when I execute the code for second time, but the change in the db will be reflected!
After 2 days of hell I finally fixed the issue by adding a statement db.settings.set('instance.cache', false) to the db config file. Though I did'nt clearly understand how db update issue was resolved by setting the cache to false, this did the trick!