meteor update - collection not updating even though it reports it does - mongodb

I'm trying to update a collection but I for some reason, even though it traces as having succeeded, when I view that collection in my console it doesn't appear to have updated.
Here's what I'm doing:
1) calling the update function from a javascript function on the client. All the values are being passed correctly:
Meteor.call('minisiteUpdater',vLayout,vColour,vBG,vHFont,vBFont,vFontColour);
2) the function itself (defined in Meteor.methods) is as follows. Note that when I log everything in the console, all the values are passed successfully into the function and the siteID I get from the session var is also correctly set. The problem is that the console is logging "success", which suggests to me that the update has worked, but when I enter Therapistminisite.find().fetch() into the console afterwards and look at the supposedly updated collection item, it has not been updated.
minisiteUpdater: function(vLayout,vColour,vBG,vHFont,vBFont,vFontColour){
var updates = { $set: {
layout: vLayout,
colour: vColour,
backgroundimage: vBG,
headingfont: vHFont,
bodyfont: vBFont,
fontcolour: vFontColour
}};
var siteID = Session.get("currentSiteBuilderID");
Therapistminisite.update(siteID, updates, function (error) {
if (error){
console.log(error);
}
else{
console.log("success");
}
});
},
Finally, just after I get the "success" logged in the console, I also get the following error message: "Error invoking Method 'minisiteUpdater': Internal server error [500]".
Anyone have any ideas?

If that is the method definition for both the server and the client,
you can't call Session.get on the server side, so that method succeeds when called in the browser, but then fails when called on the server. If you look in your server console, you should see a server error: Session is not defined corresponding to the 500 error in the browser console.
try adding the siteId as a method param, and removing the line that gets it from the session:
minisiteUpdater: function(vLayout,vColour,vBG,vHFont,vBFont,vFontColour, siteID){
var updates = { $set: {
layout: vLayout,
colour: vColour,
backgroundimage: vBG,
headingfont: vHFont,
bodyfont: vBFont,
fontcolour: vFontColour
}};
Therapistminisite.update(siteID, updates, function (error) {
if (error){
console.log(error);
}
else{
console.log("success");
}
});
},
(remove this line: var siteID = Session.get("currentSiteBuilderID");)
and then pass in Session.get("currentSiteBuilderID") when you call it from the client like this:
Meteor.call(
'minisiteUpdater',
vLayout,
vColour,
vBG,
vHFont,
vBFont,
vFontColour,
Session.get("currentSiteBuilderID")
);

Related

How to handle non explicit errors inside sails.js helpers?

I am trying to figure out how the Error handling in Sails.js works. Unfortunatley the code examples in the docs do not cover this use case.
The problem is I keep getting this error:
UsageError: `.intercept()` handler returned `undefined`, but this should never happen.
Regardless, here is a summary of the original underlying error:
Now all I am trying to do is call a helper and if it fails, then I want to catch the error (any), log it and run some code. If I wouldn't be using Sails but normal promises I would have handled it like this:
await helper().catch((err) => { // run some code }
In Sails I should be able to use .intercept() instead of .catch()
My code looks like this:
// ExportController.js
const csv = await sails.helpers.files.convertToCsv(data)
.intercept((err) => {
sails.log.error(err)
req.addFlash('error_messages', 'Error parsing data to csv!')
return res.redirect(`/`);
})
// convert-to-csv.js
if (!Array.isArray(inputs.data)) {
throw new Error('invalid inputs.data type: ' + typeof inputs.data)
};
Now how can I avoid getting this error?
The code examples show only cases where errors that are explicitly added to the exits object are handled, but not for general error handling.
In the docs it says that if the filter argument is
not provided, ALL errors will be intercepted.
Or is that only true for db queries? Because the .intercept() doc section is in that subcategory.
You could use “throw ‘errorCode’;” for example:
Set the exits:
exits {
errorWithCsvFile: {
responseType: 'badRequest'
}
}
const csv = await sails.helpers.files.convertToCsv(data)
.intercept(‘somethingWrongCode’, ‘errorWithCsvFile’)
... // Other handles
.intercept(err => new Error(err))
Alternative:
try {
...
const csv = await sails.helpers.files.convertToCsv(data)
.intercept((err) => {
sails.log.error(err)
req.addFlash('error_messages', 'Error parsing data to csv!')
throw 'badRequest';
})
...
} catch (err) {
sails.log.err(err);
return res.redirect(`/`);
}

How can I catch errors in my firebase function when setting a document fails?

I have a firebase cloud function to create a user document with user data whenever a user registers. How would I return an error when the set() fails? Since this is not an http request (an I don't want to use an http request in this case) I have no response. So how would I catch errors?
export const onUserCreated = functions.region('europe-west1').auth.user().onCreate(async user => {
const privateUserData = {
phoneNumber: user.phoneNumber
}
const publicUserData = {
name: 'Nameless'
}
try
{
await firestore.doc('users').collection('private').doc('data').set(privateUserData);
}catch(error)
{
//What do I put here?
}
try
{
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
}catch(error)
{
//What do I put here?
}
});
You can't "return" an error, since the client doesn't even "know" about this function running, there is nobody to respond to.
You can make a registration collection, and in your function make a document there for the current user (using the uid as the document id). In that document, you can put any information you'd like your user to know (status, errors, etc).
So your clients would have to add a listener to this document to learn about their registration.
In your particular code, I think the error is in doc('users'). I guess you meant doc('users/'+user.uid).
Your catch -block will receive errors that occur on your set -call:
try {
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
} catch (error) {
// here you have the error info.
}

TypeError seneca indexof if not a function during respond

I have written a simple action which connects to mongo db using seneca-mongo store module, execute a list query and get the results. I can see that the query was successful and the correct results were fetched. When I try to send these results back to the client, the respond call errors out with following message and stack trace.
ERROR act root$ OUT cmd:getparams,role:diff 11 {cmd:getparams,role:diff,payload:{id:scalaScan}} ENTRY (dqk22) - seneca: Action cmd:getparams,role:diff callback threw: k.indexOf is not a function. act_callback {message:k.indexOf is not a function,pattern:cmd:getparams,role:diff,instance:Seneca/0.7.2/d0twcki9cmxg/1485517 TypeError: k.indexOf is not a function
at /scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:851:13
at Function.forEach (/scratch/DiffAnalyzer/node_modules/lodash/dist/lodash.js:3298:15)
at Object.defaultmodify [as modify] (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:850:7)
at respond (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:654:22)
at Seneca.<anonymous> (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:401:7)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at Seneca.<anonymous> (/scratch/DiffAnalyzer/analyze.js:613:5)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at /scratch/DiffAnalyzer/node_modules/seneca-mongo-store/mongo-store.js:329:21
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:271:33
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:35
at Cursor.close (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:1009:5)
at Cursor.nextObject (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:17)
at Cursor.each (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:264:12)
The action that I have written is
seneca.add("role:diff,cmd:getparams", function(msg, respond) {
seneca.ready(function() {
var collection = seneca.make$("paramStore");
var f = msg.payload;
seneca.log.info("Filter", f);
collection.list$(f, function(err, ob) {
if (err) {
seneca.log.error(err);
respond(err);
} else {
seneca.log.info("Result", ob);
respond(null, ob);
}
});
});
});
The same piece of code was working and now I am getting this error. Not sure what changed. Any help/suggestions are greatly appreciated.
The issue I was facing was because of this bit of code in the module's js file
if( _.isObject( result.out ) ) {
_.each(result.out,function(v,k){
if(~k.indexOf('$') && 'http$' !== k) {
delete result.out[k]
}
})
The _.each function is meant to parse a JSON object, where in my case the out was actually a JSON array. Wrapping the array into an object resolved it.

Unable to Save ParseObject with User ACL in Cloud Code

I have an issue saving changes to an object from a Cloud Code function.
I have a collection called Character and one record inside it.
This Character record has an ACL with Public Read, and Private Write Access by a specific ParseUser (6MwfSLdAxd).
In Unity, I authenticated the user and I then call the Cloud Code function as follows:
ParseCloud.CallFunctionAsync<Character>("startBattle", null).ContinueWith(t =>
{
Debug.Log("I got here...");
Debug.Log(t.Result.ClassName);
});
In my Cloud Code function, I grab the first character in the collection (ignoring checking if it belongs to this user, because at the moment there is only one and it DOES belong to this user - there's only one user too).
var Character = Parse.Object.extend("Character");
Parse.Cloud.define("startBattle", function (request, response) {
var user = request.user;
if (user == null)
{
return response.error("You must login before you can battle!");
}
var characterQuery = new Parse.Query(Character);
characterQuery.first()
.then(
function (character) {
character.set("name", "Cloud Code sucka");
character.save().then(function(character) {
return response.success(character);
});
},
function (error) {
return response.error("You must create a character before you can battle! " + error);
}
)
});
However, I simply cannot save any changes to this character. All the documentation and forum posts I've found suggest that if you call a Cloud Code function when authenticated then that function should have the same level permissions as the user calling it.
The only time this code works is if I set the ACL of the character to Public Write.
Does anyone have any ideas why this wouldn't be working?
Note: Worth noting that I can see in the server logs that the Cloud Code function IS being called by the authenticated user 6MwfSLdAxd as I get this error (if I add a response.error call):
error: Failed running cloud function startBattle for user 6MwfSLdAxd with:
Input: {}
Error: {"code":141,"message":"Messed up: [object Object]"} functionName=startBattle, code=141, message=Messed up: [object Object], , user=6MwfSLdAxd
error: Error generating response. ParseError { code: 141, message: 'Messed up: [object Object]' } code=141, message=Messed up: [object Object]
[object Object]
[object Object]
After some extensive searching I've now found the solution to this.
For anyone else encountering the same issues, you should be aware that whilst Parse.com used to run Cloud Code functions in the context of the user that called them (afaik), self-hosted Parse Servers do not.
In order to call queries or saves in the context of a user you must pass their session token as shown below. I hope this saves someone the hours of confusion I went through!
var MyObject = Parse.Object.extend("MyObject");
Parse.Cloud.define("myCloudFunction", function (request, response) {
var user = request.user;
var sessionToken = user.getSessionToken();
var query = new Parse.Query(MyObject)
.find({ sessionToken: sessionToken })
.then(
function (object) {
object.set("someKey", "someValue");
return object.save(null, { sessionToken: sessionToken });
}
)
.then(
function (object) {
return response.success(object);
},
function (error) {
return response.error(error.message);
}
);
});
For further context see:
https://github.com/ParsePlatform/parse-server/wiki/Compatibility-with-Hosted-Parse#cloud-code

Configuring Restivus POST method for Meteor

I have the following Restivus configuration:
if(Meteor.isServer){
Restivus.configure({
});
//Allow Restivus to manage Reports
Restivus.addCollection('reports');
Restivus.addRoute('newReport/:message', {}, {
// POST
post: {
action: function(){
var response = null;
var message = this.urlParams.message;
if(message){
console.log("Message received: " + message);
return {status: "success", data: message};
} else {
console.log("Message empty...");
return {status: "fail", message: "Post not found"};
}
//Response to caller
return;
}
}
})
}
Following the explanation of Restivus, when I make a GET call to http://localhost:3000/api/newReport/ I should get a "Get All" result from the server, on the caller.
However, if I use curl -X GET http://localhost:3000/api/newReport/ on the command line, I seem to be getting the HTML code of the site at api/NewReport/ (which is empty, except for the header and empty body)
Knowing that, I know my error is in the Restivus Route configuration, but I cannot pinpoint the reason.
The expected behavior is that when I make a POST from a Ruby script, I should get a returned message (Ok or Fail), and in my Meteor console, I should see either "Message received" or "Post not found" (both placeholders).
Additional question, is there a way to disable the default GET method Restivus creates when we add a collection?
You have to create a variable in the JavaScript part and use that in the Restivus.addCollection() call.
Reports = Mongo.Collection('reports')
if(Meteor.isServer){
Restivus.configure({
});
//Allow Restivus to manage Reports
Restivus.addCollection(Reports);
...