Typescript not inserting into Mongo Collection - mongodb

I am using Ionic2 with Meteor/MongoDb.
I have a collection, that I am trying to insert a message object into. However, the code seems to freeze where it tries to do the insert. However, if I try insert the message object from a different place (i.e. invoke setLocalMessage(message: Message)), it does so successfully. This makes me think, the problem is not with the collection or message objects, but rather the way I am calling the function that does the insert.
private localMessageCollection: Mongo.Collection<Message> = new Mongo.Collection<Message>(null);
and
private loadMessages(): void {
let promise: Promise<string> = this.utilityService.getLoggedInPerson();
if (promise) {
promise.then((data) => {
this.personModelLoggedIn = JSON.parse(data);
if (this.personModelLoggedIn) {
this.senderId = 'P' + this.personModelLoggedIn.id;
this.title = this.activeChat.title;
this.picture = this.activeChat.picture;
this.subscribe('messages', this.activeChat._id, this.senderId, () => {
this.autorun(() => {
let promiseLocalMessages: Promise<Mongo.Collection<Message>> = this.findLocalMessages();
promiseLocalMessages.then((messageData: Mongo.Collection<Message>) => {
messageData.find().forEach((message: Message) => {
this.setLocalMessage(message);
});
});
let promiseMessages: Promise<Mongo.Collection<Message>> = this.findMessages();
promiseMessages.then((messageData: Mongo.Collection<Message>) => {
messageData.find().forEach((message: Message) => {
this.setLocalMessage(message);
});
});
});
});
} else {
this.nav.push(LoginPage, {
fromMessages: true
});
}
});
} else {
this.nav.push(LoginPage, {
fromMessages: true
});
}
}
and
private setLocalMessage(message: Message): void {
console.log('setLocalNessage: ' + message._id);
console.log(this.localMessageCollection);
this.localMessageCollection.insert(message);
console.log('setLocalNessage done: ' + message);
}
output
setLocalNessage: eC7hDZ4Z6ZwTnjP4h
Mongo.Collection {_makeNewID: function, _transform: null, _connection: null, _collection: LocalCollection, _name: null…}
but then it freezes.
If anyone can assist I would appreciate it.
UPDATE
It is freezing in the Meteor api on this line:
}Meteor.default_connection=Meteor.connection;Meteor.connect=DDP.connect}).call(this);if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package["ddp-client"]={},{DDP:DDP,LivedataTest:LivedataTest})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var DDP=Package["ddp-client"].DDP;if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package.ddp={},{DDP:DDP})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var _=Package.underscore._;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var check=Package.check.check;var Match=Package.check.Match;var EJSON=Package.ejson.EJSON;var DDP=Package["ddp-client"].DDP;var meteorInstall=Package.modules.meteorInstall;var Buffer=Package.modules.Buffer;var process=Package.modules.process;var Symbol=Package["ecmascript-runtime"].Symbol;var Map=Package["ecmascript-runtime"].Map;var Set=Package["ecmascript-runtime"].Set;var meteorBabelHelpers=Package["babel-runtime"].meteorBabelHelpers;var Promise=Package.promise.Promise;var AllowDeny;var require=meteorInstall({node_modules:{meteor:{"allow-deny":{"allow-deny.js":function(){AllowDeny={CollectionPrototype:{}};var CollectionPrototype=AllowDeny.CollectionPrototype;CollectionPrototype.allow=function(options){addValidator(this,"allow",options)};CollectionPrototype.deny=function(options){addValidator(this,"deny",options)};CollectionPrototype._defineMutationMethods=function(options){var self=this;options=options||{};self._restricted=false;self._insecure=undefined;self._validators={insert:{allow:[],deny:[]},update:{allow:[],deny:[]},remove:{allow:[],deny:[]},upsert:{allow:[],deny:[]},fetch:[],fetchAllFields:false};if(!self._name)return;self._prefix="/"+self._name+"/";if(self._connection&&(self._connection===Meteor.server||Meteor.isClient)){(function(){var m={};_.each(["insert","update","remove"],function(method){var methodName=self._prefix+method;if(options.useExisting){var handlerPropName=Meteor.isClient?"_methodHandlers":"method_handlers";if(self._connection[handlerPropName]&&typeof self._connection[handlerPropName][methodName]==="function")return}m[methodName]=function(){check(arguments,[Match.Any]);var args=_.toArray(arguments);try{var generatedId=null;if(method==="insert"&&!_.has(args[0],"_id")){generatedId=self._makeNewID()}if(this.isSimulation){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}if(method!=="insert")throwIfSelectorIsNotId(args[0],method);if(self._restricted){if(self._validators[method].allow.length===0){throw new Meteor.Error(403,"Access denied. No allow validators set on restricted "+"collection for method '"+method+"'.")}var validatedMethodName="_validated"+method.charAt(0).toUpperCase()+method.slice(1);args.unshift(this.userId);method==="insert"&&args.push(generatedId);return self[validatedMethodName].apply(self,args)}else if(self._isInsecure()){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}else{throw new Meteor.Error(403,"Access denied")}}catch(e){if(e.name==="MongoError"||e.name==="MinimongoError"){throw new Meteor.Error(409,e.toString())}else{throw e}}}});self._connection.methods(m)})()}};CollectionPrototype._updateFetch=function(fields){var self=this;if(!self._validators.fetchAllFields){if(fields){self._validators.fetch=_.union(self._validators.fetch,fields)}else{self._validators.fetchAllFields=true;self._validators.fetch=null}}};CollectionPrototype._isInsecure=function(){var self=this;if(self._insecure===undefined)return!!Package.insecure;return self._insecure};CollectionPrototype._validatedInsert=function(userId,doc,generatedId){var self=this;if(_.any(self._validators.insert.deny,function(validator){return validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.insert.allow,function(validator){return!validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(generatedId!==null)doc._id=generatedId;self._collection.insert.call(self._collection,doc)};CollectionPrototype._validatedUpdate=function(userId,selector,mutator,options){var self=this;check(mutator,Object);options=_.clone(options)||{};if(!LocalCollection._selectorIsIdPerhapsAsObject(selector))throw new Error("validated update should be of a single ID");if(options.upsert)throw new Meteor.Error(403,"Access denied. Upserts not "+"allowed in a restricted collection.");var noReplaceError="Access denied. In a restricted collection you can only"+" update documents, not replace them. Use a Mongo update operator, such "+"as '$set'.";var fields=[];if(_.isEmpty(mutator)){throw new Meteor.Error(403,noReplaceError)}_.each(mutator,function(params,op){if(op.charAt(0)!=="$"){throw new Meteor.Error(403,noReplaceError)}else if(!_.has(ALLOWED_UPDATE_OPERATIONS,op)){throw new Meteor.Error(403,"Access denied. Operator "+op+" not allowed in a restricted collection.")}else{_.each(_.keys(params),function(field){if(field.indexOf(".")!==-1)field=field.substring(0,field.indexOf("."));if(!_.contains(fields,field))fields.push(field)})}});var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.update.deny,function(validator){var factoriedDoc=transformDoc(validator,doc);return validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.update.allow,function(validator){var factoriedDoc=transformDoc(validator,doc);return!validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}options._forbidReplace=true;return self._collection.update.call(self._collection,selector,mutator,options)};var ALLOWED_UPDATE_OPERATIONS={$inc:1,$set:1,$unset:1,$addToSet:1,$pop:1,$pullAll:1,$pull:1,$pushAll:1,$push:1,$bit:1};CollectionPrototype._validatedRemove=function(userId,selector){var self=this;var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.remove.deny,function(validator){return validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.remove.allow,function(validator){return!validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}return self._collection.remove.call(self._collection,selector)};CollectionPrototype._callMutatorMethod=function(){function _callMutatorMethod(name,args,callback){if(Meteor.isClient&&!callback&&!alreadyInSimulation()){callback=function(){function callback(err){if(err)Meteor._debug(name+" failed: "+(err.reason||err.stack))}return callback}()}var firstArgIsSelector=name==="update"||name==="remove";if(firstArgIsSelector&&!alreadyInSimulation()){throwIfSelectorIsNotId(args[0],name)}var mutatorMethodName=this._prefix+name;return this._connection.apply(mutatorMethodName,args,{returnStubValue:true},callback)}return _callMutatorMethod}();function transformDoc(validator,doc){if(validator.transform)return validator.transform(doc);return doc}function docToValidate(validator,doc,generatedId){var ret=doc;if(validator.transform){ret=EJSON.clone(doc);if(generatedId!==null){ret._id=generatedId}ret=validator.transform(ret)}return ret}function addValidator(collection,allowOrDeny,options){var VALID_KEYS=["insert","update","remove","fetch","transform"];_.each(_.keys(options),function(key){if(!_.contains(VALID_KEYS,key))throw new Error(allowOrDeny+": Invalid key: "+key)});collection._restricted=true;_.each(["insert","update","remove"],function(name){if(options.hasOwnProperty(name)){if(!(options[name]instanceof Function)){throw new Error(allowOrDeny+": Value for `"+name+"` must be a function")}if(options.transform===undefined){options[name].transform=collection._transform}else{options[name].transform=LocalCollection.wrapTransform(options.transform)}collection._validators[name][allowOrDeny].push(options[name])}});if(options.update||options.remove||options.fetch){if(options.fetch&&!(options.fetch instanceof Array)){throw new Error(allowOrDeny+": Value for `fetch` must be an array")}collection._updateFetch(options.fetch)}}function throwIfSelectorIsNotId(selector,methodName){if(!LocalCollection._selectorIsIdPerhapsAsObject(selector)){throw new Meteor.Error(403,"Not permitted. Untrusted code may only "+methodName+" documents by ID.")}}function alreadyInSimulation(){var enclosing=DDP._CurrentInvocation.get();return enclosing&&enclosing.isSimulation}}}}}},{extensions:[".js",".json"]});require("./node_modules/meteor/allow-deny/allow-deny.js");if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package["allow-deny"]={},{AllowDeny:AllowDeny})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var AllowDeny=Package["allow-deny"].AllowDeny;var Random=Package.random.Random;var EJSON=Package.ejson.EJSON;var _=Package.underscore._;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var DDP=Package["ddp-client"].DDP;var Tracker=Package.tracker.Tracker;var Deps=Package.tracker.Deps;var DiffSequence=Package["diff-sequence"].DiffSequence;var MongoID=Package["mongo-id"].MongoID;var check=Package.check.check;var Match=Package.check.Match;var meteorInstall=Package.modules.meteorInstall;var Buffer=Package.modules.Buffer;var process=Package.modules.process;var Symbol=Package["ecmascript-runtime"].Symbol;var Map=Package["ecmascript-runtime"].Map;var Set=Package["ecmascript-runtime"].Set;var meteorBabelHelpers=Package["babel-runtime"].meteorBabelHelpers;var Promise=Package.promise.Promise;var LocalCollectionDriver,Mongo;var require=meteorInstall({node_modules:{meteor:{mongo:{"local_collection_driver.js":function(){LocalCollectionDriver=function LocalCollectionDriver(){var self=this;self.noConnCollections={}};var ensureCollection=function ensureCollection(name,collections){if(!(name in collections))collections[name]=new LocalCollection(name);return collections[name]};_.extend(LocalCollectionDriver.prototype,{open:function(){function open(name,conn){var self=this;if(!name)return new LocalCollection;if(!conn){return ensureCollection(name,self.noConnCollections)}if(!conn._mongo_livedata_collections)conn._mongo_livedata_collections={};return ensureCollection(name,conn._mongo_livedata_collections)}return open}()});LocalCollectionDriver=new LocalCollectionDriver},"collection.js":function(require,exports,module){Mongo={};Mongo.Collection=function(name,options){var self=this;if(!(self instanceof Mongo.Collection))throw new Error('use "new" to construct a Mongo.Collection');if(!name&&name!==null){Meteor._debug("Warning: creating anonymous collection. It will not be "+"saved or synchronized over the network. (Pass null for "+"the collection name to turn off this warning.)");name=null}if(name!==null&&typeof name!=="string"){throw new Error("First argument to new Mongo.Collection must be a string or null")}if(options&&options.methods){options={connection:options}}if(options&&options.manager&&!options.connection){options.connection=options.manager}options=_.extend({connection:undefined,idGeneration:"STRING",transform:null,_driver:undefined,_preventAutopublish:false},options);switch(options.idGeneration){case"MONGO":self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random.insecure;return new Mongo.ObjectID(src.hexString(24))};break;case"STRING":default:self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random.insecure;return src.id()};break}self._transform=LocalCollection.wrapTransform(options.transform);if(!name||options.connection===null)self._connection=null;else if(options.connection)self._connection=options.connection;else if(Meteor.isClient)self._connection=Meteor.connection;else self._connection=Meteor.server;if(!options._driver){if(name&&self._connection===Meteor.server&&typeof MongoInternals!=="undefined"&&MongoInternals.defaultRemoteCollectionDriver){options._driver=MongoInternals.defaultRemoteCollectionDriver()}else{options._driver=LocalCollectionDriver}}self._collection=options._driver.open(name,self._connection);self._name=name;self._driver=options._driver;if(self._connection&&self._connection.registerStore){var ok=self._connection.registerStore(name,{beginUpdate:function(){function beginUpdate(batchSize,reset){if(batchSize>1||reset)self._collection.pauseObservers();if(reset)self._collection.remove({})}return beginUpdate}(),update:function(){function update(msg){var mongoId=MongoID.idParse(msg.id);var doc=self._collection.findOne(mongoId);if(msg.msg==="replace"){var replace=msg.replace;if(!replace){if(doc)self._collection.remove(mongoId)}else if(!doc){self._collection.insert(replace)}else{self._collection.update(mongoId,replace)}return}else if(msg.msg==="added"){if(doc){throw new Error("Expected not to find a document already present for an add")}self._collection.insert(_.extend({_id:mongoId},msg.fields))}else if(msg.msg==="removed"){if(!doc)throw new Error("Expected to find a document already present for removed");self._collection.remove(mongoId)}else if(msg.msg==="changed"){if(!doc)throw new Error("Expected to find a document to change");if(!_.isEmpty(msg.fields)){var modifier={};_.each(msg.fields,function(value,key){if(value===undefined){if(!modifier.$unset)modifier.$unset={};modifier.$unset[key]=1}else{if(!modifier.$set)modifier.$set={};modifier.$set[key]=value}});self._collection.update(mongoId,modifier)}}else{throw new Error("I don't know how to deal with this message")}}return update}(),endUpdate:function(){function endUpdate(){self._collection.resumeObservers()}return endUpdate}(),saveOriginals:function(){function saveOriginals(){self._collection.saveOriginals()}return saveOriginals}(),retrieveOriginals:function(){function retrieveOriginals(){return self._collection.retrieveOriginals()}return retrieveOriginals}(),getDoc:function(){function getDoc(id){return self.findOne(id)}return getDoc}(),_getCollection:function(){function _getCollection(){return self}return _getCollection}()});if(!ok){var message='There is already a collection named "'+name+'"';if(options._suppressSameNameError===true){console.warn?console.warn(message):console.log(message)}else{throw new Error(message)}}}if(options.defineMutationMethods!==false){try{self._defineMutationMethods({useExisting:options._suppressSameNameError===true})}catch(error){if(error.message==="A method named '/"+name+"/insert' is already defined")throw new Error('There is already a collection named "'+name+'"');throw error}}if(Package.autopublish&&!options._preventAutopublish&&self._connection&&self._connection.publish){self._connection.publish(null,function(){return self.find()},{is_auto:true})}};_.extend(Mongo.Collection.prototype,{_getFindSelector:function(){function _getFindSelector(args){if(args.length==0)return{};else return args[0]}return _getFindSelector}(),_getFindOptions:function(){function _getFindOptions(args){var self=this;if(args.length<2){return{transform:self._transform}}else{check(args[1],Match.Optional(Match.ObjectIncluding({fields:Match.Optional(Match.OneOf(Object,undefined)),sort:Match.Optional(Match.OneOf(Object,Array,Function,undefined)),limit:Match.Optional(Match.OneOf(Number,undefined)),skip:Match.Optional(Match.OneOf(Number,undefined))})));return _.extend({transform:self._transform},args[1])}}return _getFindOptions}(),find:function(){function find(){var self=this;var argArray=_.toArray(arguments);return self._collection.find(self._getFindSelector(argArray),self._getFindOptions(argArray))}return find}(),findOne:function(){function findOne(){var self=this;var argArray=_.toArray(arguments);return self._collection.findOne(self._getFindSelector(argArray),self._getFindOptions(argArray))}return findOne}()});Mongo.Collection._publishCursor=function(cursor,sub,collection){var observeHandle=cursor.observeChanges({added:function(){function added(id,fields){sub.added(collection,id,fields)}return added}(),changed:function(){function changed(id,fields){sub.changed(collection,id,fields)}return changed}(),removed:function(){function removed(id){sub.removed(collection,id)}return removed}()});sub.onStop(function(){observeHandle.stop()});return observeHandle};Mongo.Collection._rewriteSelector=function(selector){if(LocalCollection._selectorIsId(selector))selector={_id:selector};if(_.isArray(selector)){throw new Error("Mongo selector can't be an array.")}if(!selector||"_id"in selector&&!selector._id)return{_id:Random.id()};var ret={};_.each(selector,function(value,key){if(value instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value)}else if(value&&value.$regex instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value.$regex);if(value.$options!==undefined)ret[key].$options=value.$options}else if(_.contains(["$or","$and","$nor"],key)){ret[key]=_.map(value,function(v){return Mongo.Collection._rewriteSelector(v)})}else{ret[key]=value}});return ret};function convertRegexpToMongoSelector(regexp){check(regexp,RegExp);var selector={$regex:regexp.source};var regexOptions="";if(regexp.ignoreCase)regexOptions+="i";if(regexp.multiline)regexOptions+="m";if(regexOptions)selector.$options=regexOptions;return selector}Mongo.Collection.prototype.insert=function(){function insert(doc,callback){if(!doc){throw new Error("insert requires an argument")}doc=_.extend({},doc);if("_id"in doc){if(!doc._id||!(typeof doc._id==="string"||doc._id instanceof Mongo.ObjectID)){throw new Error("Meteor requires document _id fields to be non-empty strings or ObjectIDs")}}else{var generateId=true;if(this._isRemoteCollection()){var enclosing=DDP._CurrentInvocation.get();if(!enclosing){generateId=false}}if(generateId){doc._id=this._makeNewID()}}var chooseReturnValueFromCollectionResult=function(){function chooseReturnValueFromCollectionResult(result){if(doc._id){return doc._id}doc._id=result;return result}return chooseReturnValueFromCollectionResult}();var wrappedCallback=wrapCallback(callback,chooseReturnValueFromCollectionResult);if(this._isRemoteCollection()){var result=this._callMutatorMethod("insert",[doc],wrappedCallback);return chooseReturnValueFromCollectionResult(result)}try{var _result=this._collection.insert(doc,wrappedCallback);return chooseReturnValueFromCollectionResult(_result)}catch(e){if(callback){callback(e);return null}throw e}}return insert}();Mongo.Collection.prototype.update=function(){function update(selector,modifier){for(var _len=arguments.length,optionsAndCallback=Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){optionsAndCallback[_key-2]=arguments[_key]}var callback=popCallbackFromArgs(optionsAndCallback);selector=Mongo.Collection._rewriteSelector(selector);var options=_.clone(optionsAndCallback[0])||{};if(options&&options.upsert){if(options.insertedId){if(!(typeof options.insertedId==="string"||options.insertedId instanceof Mongo.ObjectID))throw new Error("insertedId must be string or ObjectID")}else if(!selector._id){options.insertedId=this._makeNewID()}}var wrappedCallback=wrapCallback(callback);if(this._isRemoteCollection()){var args=[selector,modifier,options];return this._callMutatorMethod("update",args,wrappedCallback)}try{return this._collection.update(selector,modifier,options,wrappedCallback)}catch(e){if(callback){callback(e);return null}throw e}}return update}();Mongo.Collection.prototype.remove=function(){function remove(selector,callback){selector=Mongo.Collection._rewriteSelector(selector);var wrappedCallback=wrapCallback(callback);if(this._isRemoteCollection()){return this._callMutatorMethod("remove",[selector],wrappedCallback)}try{return this._collection.remove(selector,wrappedCallback)}catch(e){if(callback){callback(e);return null}throw e}}return remove}();Mongo.Collection.prototype._isRemoteCollection=function(){function _isRemoteCollection(){return this._connection&&this._connection!==Meteor.server}return _isRemoteCollection}();function wrapCallback(callback,convertResult){if(!callback){return}convertResult=convertResult||_.identity;return function(error,result){callback(error,!error&&convertResult(result))}}Mongo.Collection.prototype.upsert=function(){function upsert(selector,modifier,options,callback){if(!callback&&typeof options==="function"){callback=options;options={}}var updateOptions=_.extend({},options,{_returnObject:true,upsert:true});return this.update(selector,modifier,updateOptions,callback)}return upsert}();Mongo.Collection.prototype._ensureIndex=function(index,options){var self=this;if(!self._collection._ensureIndex)throw new Error("Can only call _ensureIndex on server collections");self._collection._ensureIndex(index,options)};Mongo.Collection.prototype._dropIndex=function(index){var self=this;if(!self._collection._dropIndex)throw new Error("Can only call _dropIndex on server collections");self._collection._dropIndex(index)};Mongo.Collection.prototype._dropCollection=function(){var self=this;if(!self._collection.dropCollection)throw new Error("Can only call _dropCollection on server collections");self._collection.dropCollection()};Mongo.Collection.prototype._createCappedCollection=function(byteSize,maxDocuments){var self=this;if(!self._collection._createCappedCollection)throw new Error("Can only call _createCappedCollection on server collections");self._collection._createCappedCollection(byteSize,maxDocuments)};Mongo.Collection.prototype.rawCollection=function(){var self=this;if(!self._collection.rawCollection){throw new Error("Can only call rawCollection on server collections")}return self._collection.rawCollection()};Mongo.Collection.prototype.rawDatabase=function(){var self=this;if(!(self._driver.mongo&&self._driver.mongo.db)){throw new Error("Can only call rawDatabase on server collections")}return self._driver.mongo.db};Mongo.ObjectID=MongoID.ObjectID;Mongo.Cursor=LocalCollection.Cursor;Mongo.Collection.Cursor=Mongo.Cursor;Mongo.Collection.ObjectID=Mongo.ObjectID;Meteor.Collection=Mongo.Collection;_.extend(Meteor.Collection.prototype,AllowDeny.CollectionPrototype);function popCallbackFromArgs(args){if(args.length&&(args[args.length-1]===undefined||args[args.length-1]instanceof Function)){return args.pop()}}}}}}},{extensions:[".js",".json"]});require("./node_modules/meteor/mongo/local_collection_driver.js");require("./node_modules/meteor/mongo/collection.js");if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package.mongo={},{Mongo:Mongo})})();Meteor=Package.meteor.Meteor;global=Package.meteor.global;meteorEnv=Package.meteor.meteorEnv;_=Package.underscore._;DDP=Package["ddp-client"].DDP;Mongo=Package.mongo.Mongo;Tracker=Package.tracker.Tracker;Deps=Package.tracker.Deps;

Related

Asp.net Core Can't init Hangfire using mongoDb : listIndexes failed

Hello I try to using Hangfire with mongoDb in Asp.net core app
I have an exception on the Startup.cs when launching my app which is:
Command listIndexes failed: ns does not exist: jobs.hangfire.mongo.jobParameter
I tried to create manually the collections using the prefix (jobParameter, statedata ...), but then he tried to drop them and didn't succeed
This my code in Startup.cs :
var mongoUrlBuilder = new MongoUrlBuilder("mongodb://user:pwd#localhost:27017/jobs?authSource=admin");
var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
// Add Hangfire services. Hangfire.AspNetCore nuget required
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, new MongoStorageOptions
{
MigrationOptions = new MongoMigrationOptions
{
MigrationStrategy = new MigrateMongoMigrationStrategy(),
BackupStrategy = new CollectionMongoBackupStrategy()
},
Prefix = "hangfire.mongo",
CheckConnection = true
})
);
// Add the processing server as IHostedService
services.AddHangfireServer(serverOptions =>
{
serverOptions.ServerName = "Hangfire.Mongo server 1";
});
I am currently using :
Hangfire 1.7.27
Hangfire.Mongo 0.7.27
Mongo.Driver 2.14.0
Do you have any idea ?

Error in onSnapshot: FirebaseError: [code=invalid-argument]: transaction closed

I'm recursively loading a tree stored in Firestore. The tree has ~79 nodes.
Very occasionally I'm getting this error (about one in ten full-tree loads).
Edit: the code: https://github.com/karol-depka/OrYoL
Edit: the example deployed: https://oryol.karoldepka.com/tree (sorry, no plunker for now, just this)
Details below.
Firebase version in package.json: 4.5.0
Questions:
Where can I get more info than this basic documentation https://firebase.google.com/docs/reference/js/firebase.FirebaseError
?
What is the source of the problem and how to fix it?
3VM724:27 Uncaught Error in onSnapshot: Error: transaction closed
at new FirestoreError (error.js:164)
at JsonProtoSerializer.webpackJsonp.../../../../firebase/firestore/remote/serializer.js.JsonProtoSerializer.fromRpcStatus (serializer.js:126)
at JsonProtoSerializer.webpackJsonp.../../../../firebase/firestore/remote/serializer.js.JsonProtoSerializer.fromWatchChange (serializer.js:517)
at PersistentListenStream.webpackJsonp.../../../../firebase/firestore/remote/persistent_stream.js.PersistentListenStream.onMessage (persistent_stream.js:334)
at persistent_stream.js:270
at persistent_stream.js:247
at async_queue.js:81
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
The code:
private processNodeEvents(nestLevel: number, snapshot: any, parents, listener: DbTreeListener) {
const serviceThis = this
snapshot.docChanges.forEach(function(change) {
let data = change.doc.data()
if (change.type === 'added') {
const parentsPath = serviceThis.nodesPath(parents)
console.log('node: ', nestLevel, parentsPath, data);
serviceThis.pendingListeners ++
data.node.onSnapshot(targetNodeDoc => {
serviceThis.pendingListeners --
listener.onNodeAdded(
new NodeAddEvent(parentsPath, parentsPath[parentsPath.length - 1], targetNodeDoc, targetNodeDoc.id,
serviceThis.pendingListeners))
console.log('target node:', nestLevel, targetNodeDoc)
console.log('target node title:', nestLevel, targetNodeDoc.data().title)
const subCollection = targetNodeDoc.ref.collection('subNodes')
console.log('subColl:', subCollection)
subCollection.onSnapshot((subSnap: QuerySnapshot) => {
const newParents = parents.slice(0)
newParents.push(targetNodeDoc.ref)
serviceThis.processNodeEvents(nestLevel + 1, subSnap, newParents, listener)
})
})
// console.log('root node ref: ', targetNode);
}
if (change.type === 'modified') {
console.log('Modified city: ', data);
}
if (change.type === 'removed') {
console.log('Removed city: ', data);
}
})
}
Edit: another error discovered, by running the code multiple times:
VM3343:27 Uncaught Error in onSnapshot: Error: The referenced transaction has expired or is no longer valid.
at new FirestoreError (error.js:164)
at JsonProtoSerializer.webpackJsonp.../../../../firebase/firestore/remote/serializer.js.JsonProtoSerializer.fromRpcStatus (serializer.js:126)
at JsonProtoSerializer.webpackJsonp.../../../../firebase/firestore/remote/serializer.js.JsonProtoSerializer.fromWatchChange (serializer.js:517)
at PersistentListenStream.webpackJsonp.../../../../firebase/firestore/remote/persistent_stream.js.PersistentListenStream.onMessage (persistent_stream.js:334)
at persistent_stream.js:270
at persistent_stream.js:247
at async_queue.js:81
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
window.console.error # VM3343:27
Edit: update firebase to 4.6.0, problem happened 3 times:
Uncaught Error in onSnapshot: Error: transaction closed
at new FirestoreError (error.js:149)
at JsonProtoSerializer.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/serializer.js.JsonProtoSerializer.fromRpcStatus (serializer.js:93)
at JsonProtoSerializer.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/serializer.js.JsonProtoSerializer.fromWatchChange (serializer.js:536)
at PersistentListenStream.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/persistent_stream.js.PersistentListenStream.onMessage (persistent_stream.js:309)
at persistent_stream.js:246
at persistent_stream.js:222
at async_queue.js:62
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
Edit: even if the error happens, the tree seems to continue loading.
Edit: another version of the error, with code=aborted (after upgrading firebase to 4.6.0):
Error in onSnapshot: FirebaseError: [code=aborted]: The referenced transaction has expired or is no longer valid.
/vendor.bundle.js:18588 errHandler()
/vendor.bundle.js:33367
/polyfills.bundle.js:2970 ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask()
/vendor.bundle.js:107276 Object.onInvokeTask()
/polyfills.bundle.js:2969 ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask()
/polyfills.bundle.js:2737 Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask()
/polyfills.bundle.js:3044 webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask()
/polyfills.bundle.js:3033 ZoneTask.invoke()
I have more or less the same and it is random when it works and don't. I don't use snapshot, but valueChanges
ERROR Error: transaction closed
at new FirestoreError (error.js:149)
at JsonProtoSerializer.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/serializer.js.JsonProtoSerializer.fromRpcStatus (serializer.js:93)
at JsonProtoSerializer.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/serializer.js.JsonProtoSerializer.fromWatchChange (serializer.js:536)
at PersistentListenStream.webpackJsonp.../../../../#firebase/firestore/dist/esm/src/remote/persistent_stream.js.PersistentListenStream.onMessage (persistent_stream.js:309)
at persistent_stream.js:246
at persistent_stream.js:222
at async_queue.js:62
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
For me it's this peace of code that provokes the error:
return Observable.forkJoin(entries.map(entry => {
return this.getPick(entry)
}))
each entry in entries is used to return a single pick from firestore.
private getPick(entryId: number) {
return this.afs.collection<Pick>('entry/' + entryId + '/event/' + '9/' + 'picks', ref => ref.where('is_captain','==',true))
.valueChanges()
I don't mean to hijack your thread, but I feel this is very relevant. If I change the forkJoin to
Observable.forkJoin(entries.slice(0,20)...
then it works, so I guess it is some kind of overload of queries.

Is it possible to use the OpenStack.NET SDK with SoftLayer object storage?

SoftLayer Object Storage is based on the OpenStack Swift object store.
SoftLayer provide SDKs for their object storage in Python, Ruby, Java and PHP, but not in .NET. Searching for .NET SDKs for OpenStack, I came across OpenStack.NET.
Based on this question OpenStack.NET is designed for use with Rackspace by default, but can be made to work with other OpenStack providers using CloudIdentityWithProject and OpenStackIdentityProvider.
SoftLayer provide the following information for connecting to their Object Storage:
Authentication Endpoint
Public: https://mel01.objectstorage.softlayer.net/auth/v1.0/
Private: https://mel01.objectstorage.service.networklayer.com/auth/v1.0/
Username:
SLOS123456-1:email#example.com
API Key (Password):
1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
It's not obvious how this would map to the fields of CloudIdentityWithProject, and OpenStackIdentityProvider but I tried the following and a few other combinations of project name / username / uri:
var cloudIdentity = new CloudIdentityWithProject()
{
ProjectName = "SLOS123456-1",
Username = "email#example.com",
Password = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new OpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
However, in all cases I received the following error:
Unable to authenticate user and retrieve authorized service endpoints
Based on reviewing the source code for SoftLayer's other language libraries and for OpenStack.NET, it looks like SoftLayer's object storage uses V1 auth, while OpenStack.NET is using V2 auth.
Based on this article from SoftLayer and this article from SwiftStack, V1 auth uses a /auth/v1.0/ path (like the one provided by SoftLayer), with X-Auth-User and X-Auth-Key headers as arguments, and with the response contained in headers like the following:
X-Auth-Token-Expires = 83436
X-Auth-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Url = https://mel01.objectstorage.softlayer.net/v1/AUTH_12345678-1234-1234-1234-1234567890ab
X-Trans-Id = txbc1234567890abcdef123-1234567890
Connection = keep-alive
Content-Length = 1300
Content-Type = text/html; charset=UTF-8
Date = Wed, 14 Oct 2015 01:19:45 GMT
Whereas V2 auth (identity API V2.0) uses a /v2.0/tokens path, with the request and response in JSON objects in the message body.
Based on the OpenStackIdentityProvider class in OpenStack.NET I hacked together my own SoftLayerOpenStackIdentityProvider like this:
using JSIStudios.SimpleRESTServices.Client;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenStack.Authentication;
using System;
using System.Linq;
using System.Collections.Generic;
namespace OpenStackTest1
{
public class SoftLayerOpenStackIdentityProvider : CloudIdentityProvider
{
public SoftLayerOpenStackIdentityProvider(
Uri urlBase, CloudIdentity defaultIdentity)
: base(defaultIdentity, null, null, urlBase)
{
if (urlBase == null)
throw new ArgumentNullException("urlBase");
}
public override UserAccess GetUserAccess(
CloudIdentity identity, bool forceCacheRefresh = false)
{
identity = identity ?? DefaultIdentity;
Func<UserAccess> refreshCallback =
() =>
{
// Set up request headers.
Dictionary<string, string> headers =
new Dictionary<string, string>();
headers["X-Auth-User"] = identity.Username;
headers["X-Auth-Key"] = identity.APIKey;
// Make the request.
JObject requestBody = null;
var response = ExecuteRESTRequest<JObject>(
identity,
UrlBase,
HttpMethod.GET,
requestBody,
headers: headers,
isTokenRequest: true);
if (response == null || response.Data == null)
return null;
// Get response headers.
string authToken = response.Headers.Single(
h => h.Key == "X-Auth-Token").Value;
string storageUrl = response.Headers.Single(
h => h.Key == "X-Storage-Url").Value;
string tokenExpires = response.Headers.Single(
h => h.Key == "X-Auth-Token-Expires").Value;
// Convert expiry from seconds to a date.
int tokenExpiresSeconds = Int32.Parse(tokenExpires);
DateTimeOffset tokenExpiresDate =
DateTimeOffset.UtcNow.AddSeconds(tokenExpiresSeconds);
// Create UserAccess via JSON deseralization.
UserAccess access = JsonConvert.DeserializeObject<UserAccess>(
String.Format(
"{{ " +
" token: {{ id: '{0}', expires: '{1}' }}, " +
" serviceCatalog: " +
" [ " +
" {{ " +
" endpoints: [ {{ publicUrl: '{2}' }} ], " +
" type: 'object-store', " +
" name: 'swift' " +
" }} " +
" ], " +
" user: {{ }} " +
"}}",
authToken,
tokenExpiresDate,
storageUrl));
if (access == null || access.Token == null)
return null;
return access;
};
string key = string.Format("{0}:{1}", UrlBase, identity.Username);
var userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);
return userAccess;
}
protected override string LookupServiceTypeKey(IServiceType serviceType)
{
return serviceType.Type;
}
}
}
Because some of the members of UserAccess (like IdentityToken and Endpoint) have no way to set their fields (the objects have only a default constructor and only read-only members), I had to create the UserAccess object by deserializing some temporary JSON in a similar format as returned by the V2 API.
This works, ie I can now connect like this:
var cloudIdentity = new CloudIdentity()
{
Username = "SLOS123456-1:email#example.com",
APIKey = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new SoftLayerOpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
And then get access to files etc like this:
var cloudFilesProvider = new CloudFilesProvider(identityProvider);
var containers = cloudFilesProvider.ListContainers();
var stream = new MemoryStream();
cloudFilesProvider.GetObject("testcontainer", "testfile.dat", stream);
However, is there a better way than this to use SoftLayer Object Storage from .NET?
I briefly also looked at the OpenStack SDK for .NET (a different library to OpenStack.NET), but it too seems to be based on V2 auth.

creating custom components and running with NoFlo

I am creating a custom component which interfaces with MongoDB. I wrote a CoffeeScript file which just connects to MongoDB, and stored it at noflo/components folder.
MongoBase.coffee
noflo = require "noflo"
mongodb = require "mongodb"
url = require "url"
class exports.MongoBase extends noflo.Component
constructor: ->
super
#inPorts =
url: new noflo.Port()
#inPorts.url.on "data", (data) =>
try
#parseConnectionString(data)
#MongoClient = mongodb.MongoClient;
#MongoClient.connect #serverUrl, (err, db) ->
if err
console.log("Error in connecting to MongoDB")
else
console.log("Connected to MongoDB")
catch error
console.log(error)
parseConnectionString: (connectionString) =>
databaseUrl = try
url.parse(connectionString)
catch error
console.log(error)
[..., #serverUrl, #databaseName] = databaseUrl.split('/')
#serverUrl = "mongo://" + #serverUrl
I added the following entry to component.json
"MongoBase": "components/MongoBase.coffee"
In addition to this, I created a mongo.fbp file to check the flow of the component. The FBP file has the following code:
'mongodb://localhost:27017/test' -> url DocReader(MongoBase)
On running noflo mongo.fbp, I get the following error:
/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1628
edges.forEach(function (o, i) {
^
TypeError: Object #<Object> has no method 'forEach'
at Object.parser.registerEdges (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1628:15)
at peg$c25 (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:60:50)
at peg$parseline (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:749:30)
at peg$parsestart (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:282:12)
at Object.parse (/home/saurabh/workspace/noflo/node_modules/fbp/lib/fbp.js:1650:18)
at Object.exports.loadFBP (/home/saurabh/workspace/noflo/lib/Graph.js:1065:33)
at /home/saurabh/workspace/noflo/lib/Graph.js:1116:24
at fs.js:268:14
at Object.oncomplete (fs.js:107:15)
Is there something wrong with my code, or the steps I am using to run the code?
You may have figured this out already, as it's been several month's since you asked, but I believe you need to add the getComponent() method to your class before you export it.
noflo = require "noflo"
mongodb = require "mongodb"
url = require "url"
class MongoBase extends noflo.Component
constructor: ->
super
#inPorts =
url: new noflo.Port()
#inPorts.url.on "data", (data) =>
try
#parseConnectionString(data)
#MongoClient = mongodb.MongoClient;
#MongoClient.connect #serverUrl, (err, db) ->
if err
console.log("Error in connecting to MongoDB")
else
console.log("Connected to MongoDB")
catch error
console.log(error)
parseConnectionString: (connectionString) =>
databaseUrl = try
url.parse(connectionString)
catch error
console.log(error)
[..., #serverUrl, #databaseName] = databaseUrl.split('/')
#serverUrl = "mongo://" + #serverUrl
MongoBase.getComponent = -> new MongoBase
exports.MongoBase = MongoBase
Additionally, in your graph for the component loader to work you need to specify the package your component lives in. If your package.json/component.json have a name entry like "name": "mongo-base" then you'd have to specify this in the FBP graph, like so:
'mongodb://localhost:27017/test' -> url DocReader(mongo-base/MongoBase)
N.B.: The loader clobbers any instances of 'noflo-' in the package name, so this needs to be taken into account. E.g. the name 'noflo-mongo' would get turned into just 'mongo', so when invoking the package's components you'd write in the fbp DocReader(mongo/MongoBase) and not DocReader(noflo-mongo/MongoBase).

Can't upload file to Google Drive from service account

I am trying to upload a file to google drive using google service account.
Driver Service
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
Insert File
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Main Method
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
Now, my questions is :
How and where can i check that file was uploaded?
Why it returns the file ID but list.size() is zero.
It returns the download link also but when i paste that link in
browser it doesn't download any file.
You are creating a listing request but not executing it. Use execute method to make the request:
service.files().list().execute();
If you paste the download link into the browser, it will respond with 401, because your download request should also contain a valid Authorization header. Use the following snippet to download the file programmatically.
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
InputStream stream = resp.getContent();
stream is an input stream for the file content.
Or add an Authorization: Bearer <access token> to the request you're making elsewhere.