MeteorJS insert method not inserting - javascript

I'm trying to write an app to do real time messaging as a learning tool. I've been googling for the past 4 and a half hours trying to figure out why my insert method isn't working. It doesn't throw any errors, it simply doesn't do the actual insert.
Here's the code for it:
JS client:
Template.input.events({
"keypress .input": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.user();
var message = template.find(".input").value;
alert(Meteor.call("insert", user.username, message));
template.find(".input").value = "";
}
}
});
JS Server:
Meteor.methods({
'insert':function(username, message){
Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
return "success";
},
'find': function(){
Messages.find({}, {sort: {timestamp:-1}});
}
});
HTML:
<template name="input">
<div id="input">
<input class="input" type="text" placeholder="Message..." id="message" />
</div>
</template>
I've checked using the console to confirm that nothing is being added.

Your code runs fine, and the items are saved in the DB. Just as jorjordandan and Michel mentioned it's probably caused by your publications.
An easy way to check this is to simply log what's stored. Add some logging. Since server methods always have access to all collections you can see what's actually stored.
'insert':function(username, message){
var id = Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
console.log('Inserted id: ' + id);
var insertedMessage = Messages.findOne(id);
console.log(insertedMessage);
return "success";
},
Also, as a side-note, you might reconsider posting username as a string to the server method, depending on what you're after. This can easily be manipulated by the client.
Instead you could fetch the user on server-side.
Meteor.user().username
Just make sure that the user is actually logged on, or check if Meteor.user() is undefined.

Related

check if email exists in mongodb while typing

this project uses js , mongoose , node.js
if use an email that already exists during registration to create an account, it will refresh the page clear all fields and shows a pop up message using ajax that says email exists. i dont want the fields to be cleared
im trying to fix this. the idea that i thought would be perfect is if i can use an event listener that will check the email against the database every time the user types something in the email input field. i already did this with js to make sure the passwords are identical before posting, all help and tips and remarks are welcome
here is the part of the code that checks if email exists
module.exports.signUp = async (req, res) => {
const { site_web, username, fonction, direction, email} = req.body
try {
if(email){
var check = await InscritModel.findOne({ email: email });
if(check){
res.render('inscription', { layout: 'inscription', email: true});
}
else{
// create user
}
}
}
}
UPDATE
im still stuck with this, i trying to use ajax to constantly check the email input against the database in real time, but i know im messing up a lot of things,
i created a post route in user-routes called router.post("/emailCheck", emailCheck); and in function-controller file i created this function
module.exports.emailCheck = async (email) => {
var check = await InscritModel.findOne({ email: email });
if(check){
return 1;
}
else{
return 0;}
}
this is the html input call
<input type="email" id="txtUserEmail" class="form-control" name="email" placeholder="Email.." required>
and this is the crazy ajax code
$(document).ready(function () {
$('#txtUserEmail').keyup(function () {
var email = $(this).val();
if (email.length >= 3) {
$.ajax({
url: '/emailCheck',
method: 'post',
data: { email: email },
success: function (data) {
var divElement = $('#divOutput');
if (data) {
divElement.text(' already in use');
divElement.css('color', 'red');
}
else {
divElement.text( ' available')
divElement.css('color', 'green');
}
},
error: function (err) {
alert(err);
}
});
}
});
});
its shows a one very long error message with so many things, it ends with this
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)
hopefuly ill get there, any help is appreciated, the idea i have in mind is to make ajax call a function that takes an email in its parameters and checks it against the database and returns true or false.
well, i ended up finding the solution, ill share for future people.
the goal: stop the other fields from getting cleared when the email already exists in database
the problem: verifying the email happens after the form is submit, which means the page gets refreshed
solution idea: disable the submit button, use js to listen on the email input, and verify the input against the database while the user is typing.
app.js or routes.js whatever u named it
const InscritModel = require('../models/inscrit-model');
router.get('/usercheck', function(req, res) {
console.log(req.query);
// dont forget to import the user model and change InscritModel by whatever you used
InscritModel.findOne({email: req.query.email} , function(err, InscritModel){
if(err) {
console.log(err);
}
var message;
if(InscritModel) {
console.log(InscritModel)
message = "user exists";
console.log(message)
} else {
message= "user doesn't exist";
console.log(message)
}
res.json({message: message});
});
});
in html
<div id="divOutput"></div>
<input type="email" id="usercheck" required>
<input type="submit" id="btsubmit" disabled />
in JS
$('#usercheck').on('keyup', function () {
console.log("ok");
console.log($(this).val().toLowerCase());
$.get('/usercheck?email=' + $(this).val().toLowerCase(), function (response) {
$('#divOutput').text(response.message);
var bouton = document.getElementById('btsubmit');
bouton.disabled = true;
if ($('#divOutput').html() === "user exists") {
$('#divOutput').text('Email not available').css('color', 'red');
}
else {
$('#divOutput').text('Email available').css('color', 'green');
bouton.disabled = false;
}
})
});

Meteor change database at run time

I have three database i.e, main_db it is default load database. I want load database after login.
Database are:-
main_db
->user_collection
psm_2017_db
->abc_collection
->xyz_collection
psm_2018_db
->abc_collection
->xyz_collection
Here is my project structure
here is my login script.
client
|->login
|->login.js
Template.login.rendered = function(){
SessionStore.set("login_user",false);
};
Template.login.events({
'submit #formLogin': function (event, target){
event.preventDefault();
var email = target.find('#loginEmail').value;
var password = target.find('#loginPassword').value;
// console.log(email +" "+password);
Meteor.loginWithPassword(email, password, function(err){
if(err){
console.log(err);
alert("Invalid Login!");
}
else {
SessionStore.set("login_user",true);
console.log('successfully')
Router.go("/dashboard")
}
});
}
});
Template.layout.helpers({
"isLoggedin": function () {
return SessionStore.get("login_user");
}
});
here is my load collection file
lib
|->collection.js
abcCollection=new Mongo.Collection("abc_collection");
xyzCollection=new Mongo.Collection("xyz_collection");
You can connect to multiple dbs using the below approach.
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
<<mongo_url>> is your standard mongodb url.
Eg. mongodb://127.0.0.1:27017/database_name
Now, in your specific scenario, main_db contains the user collection (I'm under the assumption that this is pertaining to meteor user collection). You need to have this loaded at all times. You can't have it load after login since user information - which is required for logging in resides in that db!
Once you take care of the above, connecting to the remaining two dbs can be done on login as below:
/lib/dbconnection.js (this will be common to both server and clinet)
Meteor.methods({
loadDB: function(){
if(Meteor.userId()){ // if a user has logged in
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
}
}
})
Meteor.call("loadDB");
loadDB will get called each time a user logs in. But I fear that it will be run each time any user logs in. In order to avoid it being re-initialized for each user login, you might want to do a check on whether database or myCollection already exists.

Using <Form>, jQuery, Sequelize and SQL to Login and route

My goal is to use the values of the IDs #username-l and #pwd-l in a html form when the user clicks the button submit, have it compare those values to values in a SQL database and if the values equal exactly the values in the database then route the user to a specified route (for now just /user is fine for testing). Currently it routes to /? with no errors which is not specified anywhere. The console shows the query is returning username = null and password = null. I have seeds in the DB called username = test password = test for testing. Any help is appreciated!
HTML:
<form id="login-form">
<div class="form-group">
<label for="username-l">Username:</label>
<input type="username" class="form-control" id="username-l" placeholder="Enter username">
</div>
<div class="form-group">
<label for="pwd-l">Password:</label>
<input type="password" class="form-control" id="pwd-l" placeholder="Enter password">
</div>
<button id="login-button" type="submit" class="btn btn-default">Login</button>
</form>
SEQUELIZE:
app.get("/api/users", function(req, res) {
db.User.findAll({
where:
{
username: req.body.username,
password: req.body.password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (req.body.username === dbUser.username && req.body.password === dbUser.password) {
res.redirect("/users");
} else {
console.log("error");
}
});
});
LOGIN.JS:
$("#login-button").on('click', function() {
var username = $("#username-l").val().trim();
var password = $("#pwd-l").val().trim();
$.get("/api/users", function(data){
console.log(data);
if (username === data.username && username === data.password) {
reRoute();
} else {
console.log("that does not exist");
}
});
});
function getUser(userData) {
$.get("/api/users", userData).then(reRoute());
}
function reRoute() {
window.location.href = "/users";
}
First of all, you're doing a GET request, which, as much as I know HTTP, dosn't have body.
Second, I'm no expert in jQuery, nor I've ever used it, but a quick Google search showed that second parameter is passed as a query string, which is how GET is supposed to work. If you have any data to send, you send it via query string, not through request body.
Therefor, the problem you have is with the server side code, where you read username and password from body instead from query string. So in order for this to work, you need to extract username and password from query like this (I'm guessing you're using Express):
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
// do the rest of the stuff with Sequelize and bussiness logic here
});
On the sidenote, you're full router callback has some bad things, like redundant checking if username and password match from the one retrieved from DB. You've already asked Sequelize to retrieve a row from the DB where username and password are the ones you recived from the frontend, and because of that, you don't need to check if instance's username and password matches the one you have. The thing you do need to check if the instance is null, because that means that there is no user with that username and password in your DB. So the "fixed" code should look something like this:
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
db.User.findAll({
where: {
username,
password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (dbUser != null) {
res.redirect("/users");
} else {
// you'd maybe like to set response status to 404
// also some user friendly error message could be good as response body
console.log("Error: user not found");
}
});
});
I hope you get the idea of the flow and where was your mistake.

Trying to pass <%> HTML Variable to Javascript - Node, Passport, and Stripe

A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.

Meteor pass data from client to server

I have a registration form, and when the user clicks the submit button the value in every textbox will be sent to server to insert that data, and return true/false.
Client:
Template.cust_register.events({
'click button': function(){
var email = $('#tbxCustEmail').val();
var msg = $('#tbxCustMsg').val();
var isSuccess = insertMsg(email,msg);
if(isSuccess){
alert("Success");
}else alert("Try again");
}
});
Server:
function insertMsg(email,msg){
Messages.insert({Email:email,Message:msg});
return true;
}
This turned out to not work.
How to solve this?
Many people said "use publish/subscribe", but I don't understand how to use that.
First, watch the introductory screencast and read the Data and security section of the docs.
Your code in a publish/subscribe model would look like this:
Common:
Messages = new Meteor.Collection('messages');
Client:
Meteor.subscribe("messages");
Template.cust_register.events({
'click button': function(){
var email = $('#tbxCustEmail').val();
var msg = $('#tbxCustMsg').val();
Messages.insert({Email:email,Message:msg});
}
});
Server:
Meteor.publish("messages", function() {
return Messages.find();
});
An alternative solution is to use Meteor.call('yourMethodName') (on the client).
Then, on the server, you can have
Meteor.methods({
yourMethodName: function() { /* validate input + return some data */ }
});
You can consider setting a session variable to the return value.
Meteor.call('yourMethodName', function (err, data) {
if (!err) {
Session.set('myData', data);
}
});
And then in some some template...
Template.whatever.helpers({
messages: function() {
return Session.get('myData');
}
});
Why do all this?
1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods.
2) You can manually determine when certain data is "refreshed".
Obviously, this methodology undermines the value of the subscription/publication model, and it should only be used in cases where real-time data isn't required.

Categories

Resources