pulling information from a remote mongoDB - javascript

I have the following code that return 0 or no result. I have no running errors
var Users_Collection = new Meteor.Collection("bp_qstat_jobs_monitor_temp");
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
if (Meteor.isClient) {
var cursor = Users_Collection.find('j_owner');
var info = cursor.count();
console.log(cursor, info);
}
so the question is what I'm doing wrong??? (the collection has 200 records)

Usually mongodb will not give error if you are finding the collection which is not available. It will give empty only. Please make sure that you are connected to the correct db, and find the collection.
Check this link for more details.

Related

Js-IPFS Error: cid.toBaseEncodedString() is not a function

I'm currently working on the backend of a website that would work similar to YouTube but only use IPFS for storage, meaning if you want to "upload" videos to the site it would already have to be on the IPFS network. The actual function is more of an Index than anything else but it was something that I wanted to tackle.
The section I'm working on is intended to verify the integrity of the CID hashes by making sure that there are still providers on the network for that specific content. If there aren't any then the CID and any information associated will get removed from my database but I'm currently getting an issue when trying using the ipfs.dhs.findProvs function.
Here is part of my code:
const ipfs = await IPFS.create({
libp2p: { config: { dht: { enabled: true } } },
});
for (var i of integrityData) {
let cid = new CID(i.CID);
console.log(cid);
let providers = ipfs.dht.findProvs(cid, { numProviders: 2 });
for await (const provider of providers) {
console.log(provider);
}
}
Error Log:
C:\Users\...\node_modules\libp2p-kad-dht\src\providers.js:202
this._log('getProviders %s', cid.toBaseEncodedString())
^
TypeError: cid.toBaseEncodedString is not a function
To further explain my code, the for loops is iterating the JSON content received the Database after querying for all the CIDs in it. i.CID does return the correct CID as a string which I then create a CID object from and pass to the function here ipfs.dht.findProvs(cid, { numProviders: 2 });. The nested for loop is there to iterate through the object that is received but I haven't made it to that stage as I keep getting the same error.

Meteor - Server-side API call and insert into mongodb every minute

I am in the process of learning Meteor while at the same time experimenting with the TwitchTV API.
My goal right now is to call the TwitchAPI every minute and then insert part of the json object into the mongo database. Since MongoDB matches on _id and Twitch uses _id as its key I am hoping subsequent inserts will either update existing records or create a new one if the _id doesnt exist yet.
The call and insert (at least the initial one) seem to be working fine. However, I can't seem to get the Meteor.setTimeout() function to work. The call happens when I start the app but does not continue occurring every minute.
Here is what I have in a .js. file in my server folder:
Meteor.methods({
getStreams: function() {
this.unblock();
var url = 'https://api.twitch.tv/kraken/streams?limit=3';
return Meteor.http.get(url);
},
saveStreams: function() {
Meteor.call('getStreams', function(err, res) {
var data = res.data;
Test.insert(data);
}
}
});
Deps.autorun(function(){
Meteor.setTimeout(function(){Meteor.call('saveStreams');}, 1000);
});
Any help or advice is appreciated.
I made the changes mentioned by #richsilv and #saimeunt and it worked. Resulting code:
Meteor.startup(function(){
Meteor.setInterval(function(){Meteor.call('saveStreams');}, 1000);
});

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.

node.js and mongodb-native: wait till a collection is non-empty

I am using node.js and with the native mongodb driver (node-mongodb-native);
My current project uses node.js + now.js + mongo-db.
The system basically sends data from the browser to node.js, which is processed with haskell and later fed back to the browser again.
Via a form and node.js the text is inserted in a mongo-db collection called "messages".
A haskell thread reads the entry and stores the result in the db collection "results". This works fine.
But now I need the javascript code that waits for the result to appear in the collection results.
Pseudo code:
wait until the collection result is non-empty.
findOne() from the collection results.
delete the collection results.
I currently connect to the mongodb like this:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var server = new Server('localhost', 27017, {
auto_reconnect: true
});
var db = new Db('test', server);
My haskell knowledge is quite good but not my javascript skills.
So I did extensive searches, but I didn't get far.
glad you solved it, i was going to write something similar:
setTimeout(function(){
db.collection('results',function(coll){
coll.findOne({}, function(err, one){
if( err ) return callback(err);
coll.drop(callback); //or destroy, not really sure <-- this will drop the whole collection
});
});
} ,1000);
The solution is to use the async library.
var async = require('async');
globalCount = -1;
async.whilst(
function () {
return globalCount<1;
},
function (callback) {
console.log("inner while loop");
setTimeout(db_count(callback), 1000);
},
function (err) {
console.log(" || whilst loop finished!!");
}
);

Finding saved data from mongo shell (no output)

Here is the code for initialization
mongoose.connect('mongodb://localhost/gpsdb');
var db = mongoose.connection;
db.on('open', function () {
// now we can start talking
});
After successful opening, I am saving data like this, it's giving me no errors.
function saveGPSData(data){
var newData = new GPSData(data);
newData.save(function(err){
if(err)
return console.error(err);
});
}
Now in mongo shell, I am trying to retrieve that data but it's giving me empty output.
> use gpsdb
> db.GPSData.find();
>
It's giving me no output. Also can I found what models are there in gpsdb?
Here is the full source code http://pastebin.com/K7QPYAx8
JUST FOUND THAT in db folder there these files for my db created by mongodb
/data/db/gpsdb.0
/data/db/gpsdb.1
/data/db/gpsdb.n
A good place to start to get a quick answer is
https://groups.google.com/forum/#!forum/mongoose-orm
the community is very responsive :)
In the shell I did the following
>use gpsdb
switched to gpsdb
>db show collections
gpsdatas
From here I found that collection name is gpsdatas...... Not sure why its adding extra (s) to my modal, although you can see from the code that I am setting Modal to
var GPSData = mongoose.model('GPSData', GPSDataSchema);
Now using the shell its working like this
>db.gpsdatas.find()

Categories