MongoDB db.collection.insertOne crashing after writing to DB - javascript

I'm currently using the 'mongodb' package to connect to a local mongo server but the application keeps crashing after creating a user. The data is been written to the local database but when the promise is calling the callback function the MongoDB package throws an error (authorization is not defined). Any ideas as of why this could be happening?
The server crashes inside the /auth/signup route. Essentially I parse the user input to check that the data provided by the user is in the correct format and then I create the structure that I'll write back to the database. I'm currently writing back a class called User with a structure like this:
class User {
strategy = ...
email = ...
displayName = ...
salt = ...
password = ...
}
After checking that no other user with this particular email has been created, I create the new User instance and insert it into mongoDB as shown below:
db.collection('users').insertOne(user, (err, result) => {
if(err){ return res.status(400).send({ error: 'failed to store new user to DB'}); }
//respond to request indicating the user was created
return res.status(200).send({token: authorization.tokenForUser(user)});
});
The application crashed after writing but before the callback. This is the error I'm getting:
.../auth/node_modules/mongodb/lib/utils.js:132
throw err;
^
ReferenceError: authorization is not defined
at db.collection.insertOne (.../auth/routes/authRoutes.js:93:45)
at result (.../auth/node_modules/mongodb/lib/utils.js:410:17)
at executeCallback (.../auth/node_modules/mongodb/lib/utils.js:402:9)
at insertDocuments (.../auth/node_modules/mongodb/lib/operations/collection_ops.js:891:19)
at handleCallback (.../auth/node_modules/mongodb/lib/utils.js:128:55)
at coll.s.topology.insert (.../auth/node_modules/mongodb/lib/operations/collection_ops.js:863:5)
at .../auth/node_modules/mongodb-core/lib/connection/pool.js:397:18
at process._tickCallback (internal/process/next_tick.js:150:11)
I believe the errors has to do with the way I'm using the mongoDB pool I initialize when the application starts running. Any help would be much appreciated.

Related

Is there a way to close the connection after using firebase.initializeApp() with Cloud Firestore?

I'm attempting to make a Discord.js command that uploads data to Cloud Firestore. It works, just if I attempt to reuse the command it reruns the firebase.initializeApp() line, which throws an error. Is there any way to disconnect after I have uploaded the data?
It is not recommended to disconnect - the time and processing cycle cost of .initializeApp() is prohibitive unless these calls are quite rare.
There are a few of valid approaches:
=> Keep a state value that indicates that the app is already initialized
=> initialize firebase at a "higher point" in your code to avoid reloading the module
=> I believe you can actually "ask" firebase if there is a running app, in which case don't re-initialize (const app = firebase.app())
If for some reason you do need to remove a firebase app instance:
const app = firebase.app(); //retrieves the default instance
app.delete()
.then(function() {
console.log("App deleted successfully");
})
.catch(function(error) {
console.log("Error deleting app:", error);
});

Discord.js read client bot token from a file rather than hard-coded

I want to be able to read the client.login(BOT_TOKEN); dynamically from a file/database, but this is getting executed before my file read function finishes executing.
BOT_TOKEN = '';
if(BUILD_PROFILE == 'dev'){
filesystem.readFile('./../devToken.txt', 'utf8', (err, data) => {
if(err) throw err;
console.log(data);
BOT_TOKEN = data;
})
}
client.login(BOT_TOKEN);
This is the error I'm getting in logs - I have double checked the file and it's console.log(data) shows the right token, but it's not being applied
I suggest you place your token in an ENV file.
I also think you should copy your token directly from your bot's bot page on discord and pasting it directly.
You console.log'd the data was it the right token?
A very easy way to do this would be to have a config.js file in your main bot folder, and set out the
{
token: “token-here”
}
Then, in your main.js file, require the config file as a variable, then at your ‘bot.login’, just do ‘bot.login(config.token)’
You can also have your prefix set in this file too, allowing a user to possibly change your command prefix in the future
Additionally, you could use a SQLite database, that saves your token - you have to have the SQLite npm library, from https://www.npmjs.com/package/sqlite here, but it is very simple to set up, if anyone needs help here, add my discord Proto#4992
n.m. SQLite databases also will come in useful when/if you want to set up a currency system in the future.

Error Running MongoDB Script on OpenShift Gear

I wrote a database population script (in JavaScript) so that I could easily run it on my local and on the server. I want to run it from the command line so that all I have to do is push it to the server/gear and execute it. The script runs fine on my local, but when I try to run it on the OpenShift gear it gives the following error:
MongoDB shell version: 2.4.9
connecting to: 127.XX.XXX.X:27017/admin
Sat Sep 12 12:20:25.979 count failed: { "ok" : 0, "errmsg" : "unauthorized" }
at src/mongo/shell/query.js:180
failed to load: ./Create.js
I'm trying to execute the command:
[xxxxxx-xxxxxx.rhcloud.com scripts]\> mongo ./Create.js
I have included the innards of my file. I left out all the document creation stuff. Just know I added document to an array.
// Switch to the DB we want
var connection;
try {
// Try to connect to local first
connection = new Mongo();
}
catch(err) {
// If error, connect to OpenShift server
connection = new Mongo('127.XX.XXX.X:27017');
}
db = connection.getDB('xxxxxxx');
// Create array to store documents
var newDocs = [];
...
// Documents are added to newDocs here
...
// If any new documents exist, insert them
if(newDocs.length) {
var bulk = db.xxxxxxx.initializeUnorderedBulkOp();
newDocs.forEach(function (doc) {
bulk.insert(doc);
});
bulk.execute();
print('NEW DOCS INSERTED');
}
else {
print('NO NEW DOCS');
}
Looks like you are missing your username/password to connect to your mongodb database on openshift? look at the error you got "unauthorized..."
I used db.auth('username', 'password'); to authenticate. Ultimately, I added a variable to the script to track if I was running the script locally or on the server. Then I used a variable for the password so that I wouldn't have the DB password just hanging out in the script. I pass the password in from the command line with the --eval option. Here is the altered head of the script:
// Switch to the DB we want
var connection;
var isLocal = true;
try {
// Try to connect to local first
connection = new Mongo();
}
catch(err) {
// If error, connect to OpenShift server
connection = new Mongo('127.XX.XXX.X:27017');
isLocal = false;
}
db = connection.getDB('xxxxxxx');
if(!isLocal) {
// If on server, authenticate
db.auth('username', password);
}
// Create array to store documents
var newDocs = [];
Then, to run the script from the command line on the server, I use the following:
mongo --eval "var password = 'xxxxxxx';" Create.js

Error when sending message with realtime.co - Boolean is not a function

I am using realtime.co for realtime messaging in my .NET 4.5/Javascript webapp.
I created a connection using the code:
xRTML.ready(function () {
xRTML.Config.debug = true;
globalRealtimeConnectionId = generateUUID();
globalRealtimeToken = getRealtimeToken();
globalMyConnection = xRTML.ConnectionManager.create(
{
id: globalRealtimeConnectionId,
appkey: 'xxxx',
authToken: globalRealtimeToken, // insert token
url: 'http://ortc-developers.realtime.co/server/2.1'
});
globalMyConnection.bind(
{
// When we get a message, process it
message: function (e) {
var user = e.message; // the use that just joined
}
});
globalMyConnection.active = true;
});
On the server I gave permissions to "main:*" (all sub channels) and returned a token.
When I send a message to the user from the server using the following code:
OrtcClient client = (OrtcClient)Application["realtime"]; // get reference to client, which initialized in global.asax
client.Send(channel, user); // send message
user is a string with the username, channel is the channel name (e.g. main:12_323_34_. I get the following error in xrtml-custom-3.2.0-min.js:1
Uncaught TypeError: boolean is not a function xrtml-custom-3.2.0-min.js:1
c.Connection.process
(anonymous function)
f.proxy
IbtRealTimeSJ.d.sockjs.d.sockjs.onmessage
x.dispatchEvent
m._dispatchMessage
m._didMessage
m.websocket.d.ws.onmessage
From what I can tell, the client is subscribed because it triggers something when a message is sent to it from the server. But I can't understand the source of the error. Because of the error, the function binded to "message:" is not triggered.
For debugging purposes, if I were you, I would include the non-minified version so you can see exactly what function is causing the error. Once you've done that, it should be easier to track down.
One other quick note is when making RESTful calls you should try to do this in the back end so your api key is not exposed to the public. This would obviously only be an issue when you are creating a public facing website, so if this is an organizational (internal) application you can disregard.

Need to run code on save and log from Parse Cloud Code when updating PFObject's key in iOS app

I have a PFObject that has an array key. I can successfully call addObject: on this PFObject, and can confirm that the object has been added to the array key properly using an NSLog. However, when I try to save the PFObject to Parse, even though it says everything went successful, the changes are not shown in the Data Browser.
I have tried everything, and can even get this to work in an older version of my app, but for some reason it will not work anymore.
I posted another StackOverflow question about this here
The only response I got were some comments saying that I should trigger a "before save" function and log everything via Cloud Code. The problem is I don't know javascript, and I've been messing around with Cloud Code and nothing's happening.
Here is the code I am executing in my app:
[self.message addObject:currentUsersObjectId forKey:#"myArrayKey"];
And then I am using saveInBackgroundWithBlock:
I need to alter Cloud Code so that it will check the self.message object's "myArrayKey" before saving and log the results.
Edit 2:
Here is how I create currentUsersObjectId:
NSString *currentUsersObjectId = [[NSString alloc]init];
PFUser *user = [PFUser currentUser];
currentUsersObjectId = user.objectId;
Edit 3:
Here is the save block
[self.message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"An error has occurred.");
}
}];
Edit 4:
After adding Timothy's cloud code, the saveInBackgroundWithBlock: now does not successfully complete. Instead an error occurs, and the error object NSLogs as `"Error: Uncaught Tried to save an object with a pointer to a new, unsaved object. (Code: 141, Version: 1.2.17)" and also as:
Error Domain=Parse Code=141 "The operation couldn’t be completed. (Parse error 141.)" UserInfo=0x15dc4550 {code=141, error=Uncaught Tried to save an object with a pointer to a new, unsaved object.} {
code = 141;
error = "Uncaught Tried to save an object with a pointer to a new, unsaved object.";
}
Here is my complete Cloud Code file after adding Timothy's 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 });
var currentUser = request.user;
var relation = user.relation("friendsRelation");
relation.add(currentUser);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
After much back and forth, I'm stumped as to why this isn't working for you. As for logging in Cloud Code, if you follow the guide on adding code you can add the following to your main.js and deploy it:
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
With those in place you have plenty of server-side logging that you can check.
I am adding my own answer in addition to Timothy's in case anyone else is having a problem similar to this. My app uses the following library to allow parse objects to be stored using NSUserDefaults: https://github.com/eladb/Parse-NSCoding
For whatever reason, after unarchiving the parse objects, they are not able to be saved properly to the Parse database. I had to query the database using the unarchived one's objectId and retrieve a fresh version of the object, and then I was able to successfully make changes to and save the retrieved object.
I have no idea why this is happening now. I have never had any problems until about two weeks ago when I tried to deploy a new version of my cloud code, and if I remember correctly, Parse wanted me to update the Parse SDK or the Cloud Code version before I could deploy it.
These changes must not be compatible with these categories.

Categories