Meteor: Autoform not submitting posts to mongo - javascript

I am new to meteor and autoform and am trying to get a form to insert into mongo. No matter what I have changed it just will not work. I have no idea what to try next.
I have removed insecure and autopublish. Attached is a link to my .js and my html file.
I have setup a scheme, gotten the form to show on the html perfectly. now when I hit submit nothing is being put into mongo. I have allow rules setup. I have a ton of console.logs displaying and they all trigger and follow along as if the post was successful. In fact in the onSuccess I get a document number yet there is nothing in my DB.
Any help here is greatly appreciated. I know it must be something small here but I have racked my brain for hours of endless searching.
.js file without the scheme. Full js file in the plnkr link
if (Meteor.isClient) {
// ********************************************************
// *** Creating the database scheme for the customer account
// ********************************************************
customers = new Mongo.Collection("customer");
AutoForm.debug();
var postHooks = {
before: {
insert: function(doc) {
console.log("Getting to posting hooks");
if(Meteor.userId()){
doc.createdUser = Meteor.userId();
doc.createdDate = Date();
console.log("Got to the insert before hook!");
}
return doc;
}
},
after: {
// Replace `formType` with the form `type` attribute to which this hook applies
insert: function(error, result) {
console.log("Getting to the after insert function");
console.log(error);
console.log(result);
console.log("New Document ID is " + this.docId);
}
},
onSuccess: function(formType, result) {
console.log("Getting to the insert sucess area");
console.log(result);
},
onError: function(formType, error) {
console.log(error);
}
}
AutoForm.addHooks('insertCustomer', postHooks);
Template.customerTemplate.helpers({
showLoginError: function(){
return showCustomerSaveError;
}
});
}
if (Meteor.isServer) {
customers = new Mongo.Collection("customer");
customers.allow({
insert: function (userId, doc) {
console.log("Getting to the insert server call");
// the user must be logged in
return !! userId;
},
update: function (userId, doc, fields, modifier) {
// can only change your own documents
return doc.owner === userId;
},
remove: function (userId, doc) {
// can only remove your own documents
return doc.owner === userId;
},
fetch: ['owner']
});
}
http://plnkr.co/edit/5pM0Co9luGLIBBNKP5YA

You're adding the file to the database but not publishing it.
Run meteor add autopublish or check in MongoDB itself to see the document.

Related

load query every second using node js

I want to select data after inserting, so what i want is to check it every second if there is a new data. I create a select query then try to display it using console log. Please help me, I'm a newbie. Here is my code
Controller
var connection = require('../../config/db');
function myQuery(callback) {
this.pushActivity = function(req, res, next) {
var salesman_id = req.query.salesman_id
connection.acquire(function(err, con) {
con.query('SELECT * FROM `activities` where salesman_id="'+salesman_id+'" and kunci="0" and created=NOW()', function(err, data) {
con.release();
if (err) {
return res.json({ status: 400, message: 'Failed', result: [] });
} else {
console.log(data)
// return res.json(data);
}
});
});
};
callback();
}
function wait10sec(){
setTimeout(function(){
myQuery(wait10sec);
}, 10000);
}
myQuery(wait10sec);
module.exports = new myQuery();
Router
var ad =
require('./../../controllers/mobile/activity_after_deal');
module.exports = {
configure: function(app) {
app.route('/api_ad_push_notif').get(ad.pushActivity);
}
};
This is not a good and efficient approach .Instead of using this ,try to use listener on put request which changes the data and after change event,execute the Get query and output the changed data.Use Socket.io Library for such purposes.
you can use socket.io .
by this module you can send live event to server and get response.
for example when send new data, you can select query or send emit to user or show it on console log
You can create worker by adding
setInterval(function(){
//run query and console
}, 1000) and you can set time

CouchDB Cannot update a Document via nano module

I'm using This Node.js module nano
Why I Can't Update my Document? I will Want to Make crazy: true and then False again.
This is My Code:
var nano = require('nano')('http://localhost:5984');
// clean up the database we created previously
nano.db.destroy('alice', function() {
// create a new database
nano.db.create('alice', function() {
// specify the database we are going to use
var alice = nano.use('alice');
// and insert a document in it
alice.insert({ crazy: true }, 'rabbit', function(err, body, header) {
if (err) {
console.log('[alice.insert] ', err.message);
return;
}
console.log('you have inserted the rabbit.')
console.log(body);
});
});
});
Nano doesn’t come with an update method by default. That is why we need to define a custom method that would do it for us. Declare the following near the top of your app.js file, right after your database connection code.
test_db.update = function(obj, key, callback){
var db = this;
db.get(key, function (error, existing){
if(!error) obj._rev = existing._rev;
db.insert(obj, key, callback);
});
}
You can then use the update method in your code:
// and update a document in it
alice.update({ crazy: false }, 'rabbit', function(err, body, header) {
if (err) {
console.log('[alice.insert] ', err.message);
return;
}
console.log('you have updated the rabbit.')
console.log(body);
});
});
});

Parse Server / JS SDK, error 206 when saving a user object

I am having trouble using the Parse Server JS SDK to edit and save a user.
I am signing in, logging in and retrieving the user just fine, I can call without exception user.set and add/edit any field I want, but when I try to save, even when using the masterKey, I get Error 206: Can t modify user <id>.
I also have tried to use save to direcly set the fields, same result.
A interesting thing is that in the DB, the User's Schema get updated with the new fields and types.
Here is my update function:
function login(user, callback) {
let username = user.email,
password = user.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(user, callback) {
login(user, (error, user) => {
if(error) {
callback('Can t find user');
} else {
console.log('save');
console.log('Session token: ' + user.getSessionToken());
console.log('Master key: ' + Parse.masterKey);
user.set('user', 'set');
user.save({key: 'test'}, {useMasterKey: true}).then(
(test) => {
console.log('OK - ' + test);
callback();
}, (err) => {
console.log('ERR - ' + require('util').inspect(err));
callback(error.message);
}
);
}
});
}
And a exemple of the error:
update
save
Session token: r:c29b35a48d144f146838638f6cbed091
Master key: <my master key>
ERR- ParseError { code: 206, message: 'cannot modify user NPubttVAYv' }
How can I save correctly my edited user?
I had the exact same problem when using Parse Server with migrated data from an existing app.
The app was created before March 2015 when the new Enhanced Sessions was introduced. The app was still using legacy session tokens and the migration to the new revocable sessions system was never made. Parse Server requires revocable sessions tokens and will fail when encountering legacy session tokens.
In the app settings panel, the Require revocable sessions setting was not enabled before the migration and users sessions were not migrated to the new system when switching to Parse Server. The result when trying to edit a user was a 400 Bad Request with the message cannot modify user xxxxx (Code: 206).
To fix the issue, I followed the Session Migration Tutorial provided by Parse which explain how to upgrade from legacy session tokens to revocable sessions. Multiple methods are described depending on your needs like enableRevocableSession() to enable these sessions on a mobile app, if you're only having a web app, you can enforce that any API requests with a legacy session token to return an invalid session token error, etc.
You should also check if you're handling invalid session token error correctly during the migration to prompt the user to login again and therefore obtain a new session token.
I had the same error and neither useMasterKey nor sessionToken worked for me either. :(
Here's my code:
console.log("### attempt 1 sessionToken: " + request.user.getSessionToken());
var p1 = plan.save();
var p2 = request.user.save(null, {sessionToken: request.user.getSessionToken()});
return Parse.Promise.when([p1, p2]).then(function(savedPlan) {
...
}
I see the matching session token in log output:
2016-08-21T00:19:03.318662+00:00 app[web.1]: ### attempt 1 sessionToken: r:506deaeecf8a0299c9a4678ccac47126
my user object has the correct ACL values:
"ACL":{"*":{"read":true},"PC7AuAVDLY":{"read":true,"write":true}}
I also see a bunch of beforeSave and afterSave logs with user being "undefined". not sure whether that's related.
beforeSave triggered for _User for user undefined:
I'm running latest parser-server version 2.2.18 on Heroku (tried it on AWS and results are the same)
function login(logInfo, callback) {
let username = logInfo.email,
password = logInfo.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(userInfo, data, callback) {
login(userInfo, (error, user) => {
if(error) {
callback('Can t find user');
} else {
getUpdatedData(user.get('data'), data, (error, updateData) => {
if(error) {
callback(error);
} else {
user.save({data: updateData}, /*{useMasterKey: true}*/ {sessionToken: user.get("sessionToken")}).then(
(test) => {
callback();
}, (err) => {
callback(error.message);
}
);
}
});
}
});
}
For some reason, retrying to use sessionToken worked.
This is not how asynchronous functions work in JavaScript. When createUser returns, the user has not yet been created. Calling user.save kicks off the save process, but it isn't finished until the success or error callback has been executed. You should have createUser take another callback as an argument, and call it from the user.save success callback.
Also, you can't create a user with save. You need to use Parse.User.signUp.
The function returns long before success or error is called.

Parse iOS SDK + Cloud Code: How to update user

I am confused on how to update a user from cloud code. If someone can help me out with getting my mind right about this I'd appreciate it.
The cloud code I will use for this example is:
cloud code
Parse.Cloud.define("like", function(request, response) {
var userID = request.params.userID;
var User = Parse.User();
user = new User ({ objectId: userID });
user.increment("likes");
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
called from iOS
[PFCloud callFunctionInBackground:#"like" withParameters:#{#"userID": self.selectedFriendID} block:^(id object, NSError *error) {
}];
Questions
user = new User ({ objectId: userID });
1) is the "new" in the code above creating a "brand new" user, or is it "grabbing" an existing user at the objectId so that it can be updated on user.save?
2) if the latter is correct, than is it possible to "grab" a user from a column other than the objectId column, and maybe instead grab from the userID column?
eg:
user = new User ({ userID : userID });
This line:
user = new User ({ objectId: userID });
Creates an instance of an object with a known ID, it only works with objectId. Any changes you make to that object are persisted, but no other data is changed (e.g. you won't accidentally blank out the other columns).
If instead you wanted to get a user by email you would have to do a query:
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('email', userEmail);
userQuery.first().then(function(user) {
if (user) {
// do something with the user here
user.set('new_col', 'new text');
user.save().then(function() {
response.success();
});
} else {
// no match found, handle it or do response.error();
}
});
// the above code is async, don't put anything out here and expect it to work!
What I would do to retrieve the user in cloud code is query.get(request.params.userID.... I believe this returns the user object. I do not know if you can do this with other columns. There is lots of stuff in the cloud code docs about this, though. Here is my cloud code function for editing a user, if that helps:
Parse.Cloud.define("editUser", function(request, response) {
//var GameScore = Parse.Object.extend("SchoolHappening");
// Create a new instance of that class.
//var gameScore = new GameScore();
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.get(request.params.myUser, {
success: function(myUser) {
// The object was retrieved successfully.
myUser.set("cabinetPosition", request.params.myPosition);
// Save the user.
myUser.save(null, {
success: function(myUser) {
// The user was saved successfully.
response.success("Successfully updated user.");
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
response.error("Could not save changes to user.");
}
});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
});

Parse.com: getting UserCannotBeAlteredWithoutSessionError

I have an Angular service that takes in a roleId and userId and assigns the user to that role and make a pointer in User to that role.
app.service('CRUD', function () {
this.addUserToRole = function (roleId, userId) {
// first we have to find the role we're adding to
var query = new Parse.Query(Parse.Role);
return query.get(roleId, {
success: function (role) {
// then add the user to it
var Database = Parse.Object.extend("User");
var query = new Parse.Query(Database);
console.log(role);
return query.get(userId, {
success: function (user) {
console.log(user);
role.getUsers().add(user);
role.save();
// now we need to tell the user that he has this role
console.log(user);
user.attributes.role.add(role);
user.save();
return user;
},
error: function (err) {
return err;
}
});
},
error: function (err) {
console.log(err);
}
});
}
});
I'm getting {"code":206,"error":"Parse::UserCannotBeAlteredWithoutSessionError"} on user.save();
After some research, I arrived at this website. He uses this code snippet as a JS SDK example:
Parse.Cloud.run('modifyUser', { username: 'userA' }, {
success: function(status) {
// the user was updated successfully
},
error: function(error) {
// error
}
});
and mentions something about a useMasterKey() function.
I'm still unsure how to fix this error.
Add
Parse.Cloud.useMasterKey();
at the beginning of your function.
Set it up as a background job. That is the code snip you found I think and a simpler far more secure means of fondling users and roles
https://parse.com/docs/cloud_code_guide#jobs

Categories