how to update a Mongo.db collection in meteor.js? - javascript

I have a collection that I need to update when the user presses a button.
I just need to change one variable to another.
In the console, this line of code works:
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
But when I put in this code:
Template.body.events({
'click #updateAge' = function() {
{
alert();
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
}
}
})
into my JavaScript file for Meteor.js, it doesn't do anything at all (I don't get an error message, and I see the alert, but the update just doesn't work).
I've read through the Meteor Documentation on updating, but I just can't seem to get it to work.
Does anybody know what I'm doing wrong here?

Found the problem.
Since I defined my database in my lib.js file
users = new Meteor.collection("users");
I don't need to put a db in front of the db.users.update({_id : "Jack"},{...}). I also need to find the document using the given mongo _id, not the identifier "username".
so the appropriate code would be
users.update({_id : "Jack"},{$set:{age : 13, username : "Jack"}});

In mongodb, you will have to use an update operator(for ex: $set). Otherwise, your document will overwritten by the update object you are passing(I am not sure that's what you want). I think, its works same in meteor. So, you will have to do something like this:
Meteor.users.update({username : "Jack"},{$set: {age : 13}});

This might not be the problem as you've stated you do not get a error message but to be sure: have you already allowed the user to update documents in the user collection?
Something like:
(in collections/permissions.js)
user.allow({
update: function (userId) {
// the user must be logged in to allow updates
return (userId != null);
}
})

Related

Firebase retrieves snapshot value as null

I use the .once( function in Firebase and am successfully retrieving the snapshot.key NAME of the directory. But this key has also a value.
When requesting snapshot.val() also gives out null despise it having a value.
The database looks like this:
stages {
stage1AVERYLONGHASH : "values i want to get"
stage2AVERYLONGHASH : "values i want to get"
}
My code
var ref = "stage1AVERYLONGHASH";
var branch = firebase.database().ref(ref).once('value').then(function(s){
console.log(s.key); // GIVES THE CORRECT ANSWER
console.log(s.val()); //GIVES null ... doesn't give me the "values i want.."
Am i doing it completely wrong?
I'm new to Firebase.
Please know that the database is structured like this intentionally.
I restricted read permission on "stages".
The game works as just requesting a hash from the database as a reference, to get contents.
I think you suppose to get the reference of the stage and then get the stage1 reference from him like :
.ref("stage").child("stage1")
I'm not sure about the actual syntax but I know that this is how I get my firebase data in android studio

Get _id after Accounts.createUser

I'm trying to create a new user and use their _id for another collection right after it's created.
var newUserId = Accounts.createUser({username: "w/e", password:"w/e"});
doesn't work as I thought.
I know if you insert something into a collection it returns the _id, so I'd assume this would be same, but apparently it's not.
"newUserId" ends up being undefined.
I'm not sure if this matter, but I'm creating the user via server side.
Any helps is appreciated, thanks.
*Solved:
Got the code to do what it needed to do.
Accounts.validateNewUser(function (user){
//do something after user creation
});
slap that code into the account.js in the server side.
Once the user was created via
Accounts.createUser({})
the method:
Account.validateNewUser()
fire immediately afterward. Used the user argument to get whatever the new user properties I need (in this case the _id and username) and plugged that into another collection meteor method.
Thanks again!
PS: turns out
Accounts.createUser({})
Actually does return the _id, but you can only see it in the server console, but not the client console, so I apologize for any confusion. That was my mistake.
To debug this, specify a callback then look at the error that is being returned.
Accounts.createUser({username: "w/e", password: "w/e", function(err){
if ( err ) console.log(err);
}

Can you list users in Meteor without a login system?

For example, if I did a chatroom where all you ahve to do is enter a username (so you don't log in), can I still somehow list out all the people in that chatroom? How can I do this?
Instead of using the normal Meteor.users collection, it would probably be easiest to create your own collection for such simple authentication.
If you wanted to make it really simple (most likely, as long as you didn't care if 2 people have the same name), just store the name as a property of a chat room message document.
Edit - answer to comment:
To detect when a user disconnects, you can add an event handler in your publish function like this:
Meteor.publish('some_collection', function(){
var connectionId = this.connection ? this.connection.id : 'server';
this._session.socket.on("close", Meteor.bindEnvironment(function(){
// deal with connectionId closing
}));
});
You can do that.
Simply publish all users and every coming client should subscribe.
server:
Meteor.publish('allUsers', function(){
return Meteor.users.find({},{fields:{profile:1}});
})
client :
Meteor.startup(function(){
Meteor.subscribe('allUsers');
})
Template.listOfUsers.users = function(){
return Meteor.users.find();
}
This is very basic example, which should be adjusted to your needs.

Parse iOS SDK: Understanding Cloud Code

Scenario = I am slowly but surely wrapping my head around what is going on with Parse's cloud code features. I just need some help from those who would like to answer some short, relatively simple questions about what is going on in some sample cloud code functions.
The code I will use in this example is below
1) cloud code
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
2) called from iOS
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
This code was taken from here
Question 1 =
(request, response)
I am confused by what this is. Is this like typecasting in iOS where I am saying (in the iOS call) I want to pass an NSString into this function ("userId") and inside the cloud code function I'm going to call it "request"? Is that what's going on here?
Question 2 =
Parse.Object.extend('_User')
Is this grabbing the "User" class from the Parse database so that a "PFObject" of sorts can update it by creating a new "user" in the line below it?
Is this like a...
PFObject *userObject = [PFObject objectWithClassName:#"User"]?
Question 3 =
user.set('new_col', newColText)
This obviously 'sets' the values to be saved to the PFUser (~I think). I know that the "newColText" variable is the text that is to be set - but what is 'new_col'? Only thing I can think of is that this sets the name of a new column in the database of whatever type is being passed through the "request"?
Is this like a...
[[PFUser currentUser] setObject: forKey:]
Question 4 =
Parse.Cloud.useMasterKey()
Without getting too technical, is this basically all I have to type before I can edit a "User" object from another User?
Question 5 =
user.save().then(function(user) {
response.success(user);
}
Is this like a...
[user saveInBackgroundWithBlock:]?
and if so, is
function(error) {
response.error(error)
just setting what happens if there is an error in the saveInBackgroundWithBlock?
Please keep in mind, I know iOS - not JavaScript. So try to be as descriptive as possible to someone who understands the Apple realm.
Here's my take on your questions:
The request parameter is for you to access everything that is part of the request/call to your cloud function, it includes the parameters passed (request.params), the User that is authenticated on the client (request.user) and some other things you can learn about in the documentation. The response is for you to send information back to the calling code, you generally call response.success() or response.error() with an optional string/object/etc that gets included in the response, again documentation here.
That's a way of creating an instance of a User, which because it is a special internal class is named _User instead, same with _Role and _Installation. It is creating an instance of the user with an ID, not creating a new one (which wouldn't have an ID until saved). When you create an object this way you can "patch" it by just changing the properties you want updated.
Again, look at the documentation or an example, the first parameter is the column name (it will be created if it doesn't exist), the second value is what you want that column set to.
You have to do Parse.Cloud.useMasterKey() when you need to do something that the user logged into the client doesn't have permission to do. It means "ignore all security, I know what I'm doing".
You're seeing a promise chain, each step in the chain allows you to pass in a "success" handler and an optional "error" handler. There is some great documentation. It is super handy when you want to do a couple of things in order, e.g.
Sample code:
var post = new Parse.Object('Post');
var comment = new Parse.Object('Comment');
// assume we set a bunch of properties on the post and comment here
post.save().then(function() {
// we know the post is saved, so now we can reference it from our comment
comment.set('post', post);
// return the comment save promise, so we can keep chaining
return comment.save();
}).then(function() {
// success!
response.success();
}, function(error) {
// uh oh!
// this catches errors anywhere in the chain
response.error(error);
});
I'm pretty much at the same place as you are, but here are my thoughts:
No, these are the parameters received by the function. When something calls the editUser cloud function, you'll have those two objects to use: request & response. The request is basically what the iOS device sent to the server, and response is what the server will send to the iOS device.
Not quite that. It's like creating a subclass of _User.
Think of Parse objects types as a database table and it's instances as rows. The set will set (derp) the value of 'newColText' to the attribute/column 'new_col'.
Not sure, never used that function as I don't handle User objects. But might be that.
Pretty much that. But it's more sort of like (pseudo-code, mixing JS with Obj-C):
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if(error){
response.error(error); // mark the function as failed and return the error object to the iOS device
}
else{
response.success(user); // mark the function call as successful and return the user object to the iOS device
}
}];

'POST 400 bad request' error when updating parse.com table

I am getting a 'POST 400 bad request' error when trying to update a table on parse.com using JS SDK.
var Gallery = Parse.Object.extend("Gallery");
var gallery = new Gallery();
var activeArtworks = 0;
gallery.save(null, {
success: function(gallery) {
gallery.set("activeArtworks", activeArtworks);
gallery.save();
}
});
Please help!
I can't see how this is any different to the sample code provided by parse here
The sample code you reference creates all of its parameters before setting up the save() method. This is the step you're missing; you need to create the activeArtworks parameter on your gallery instance. Your update is failing because you're trying to update a property that was never created.
I would expect this code to work, though I didn't test it because parse.com requires you to set up an account to run any code, which is silly, and I didn't feel like creating one:
var Gallery = Parse.Object.extend("Gallery");
var gallery = new Gallery();
var activeArtworks = 0;
gallery.activeArtworks = []; // or some more appropriate default if you have one.
gallery.save(null, {
success: function(gallery) {
gallery.set("activeArtworks", activeArtworks);
gallery.save();
}
});
It might also be worth checking if there's any info in the headers of the 400 error (the debug console in your browser will show these in its Network tab). I would expect Parse to give you some sort of information to help you debug issues, and that's the only place it would fit for an HTTP error.
If you had use user.logIn(callback) function with Parse JS, maybe your session invalid. Please check your callback function error code, if error.code==209 (invalid session token), use Parse.User.logOut() and re-login again.
Like this:
if (error.code == 209) {
Parse.User.logOut();
user.logIn(loginCallback);
return;
}
I had this same issue and it was resolved after realising that the data type that I was posting was different to that specified in the columns that I had created.
In my case, I was trying to save an object when I had specified an array when creating the column in the class.

Categories