Basically, I am trying to get a wss feed going from Poloniex, and update a collection with it so that I can have 'latest' prices in a collection (I will update and overwrite existing entries) and show it on a web page. For now, I got the wss working and am just trying to insert some of the data in the collection to see if it works, but it doesn't and I can't figure out why!
Note: The collection works, I've manually inserted a record with the shell.
Here is the code I have now:
import { Meteor } from 'meteor/meteor';
import * as autobahn from "autobahn";
import { Mongo } from 'meteor/mongo'
import { SimpleSchema } from 'meteor/aldeed:simple-schema'
//quick DB
Maindb = new Mongo.Collection('maindb');
Maindb.schema = new SimpleSchema({
place: {type: String},
pair: {type: String},
last: {type: Number, defaultValue: 0}
});
Meteor.startup(() => {
var wsuri = "wss://api.poloniex.com";
var Connection = new autobahn.Connection({
url: wsuri,
realm: "realm1"
});
Connection.onopen = function(session)
{
function tickerEvent (args,kwargs) {
console.log(args[0]);
Maindb.insert({place: 'Poloniex', pair: args[0]});
}
session.subscribe('ticker', tickerEvent);
Connection.onclose = function () {
console.log("Websocket connection closed");
}
}
Connection.open();
});
The console logs the feed but then the insert does not work.
I looked online and it said that to get an insert to work when in a 'non Meteor' function, you need to use Meteor.bindEnvironment which I did:
I changed
function tickerEvent (args,kwargs) {
console.log(args[0]);
Maindb.insert({place: 'Poloniex', pair: args[0]});
}
which became
var tickerEvent = Meteor.bindEnvironment(function(args,kwargs) {
console.log(args[0]);
Maindb.insert({place: 'Poloniex', pair: args[0]});
}); tickerEvent();
Which doesn't do anything - not even print the feed on my console. Using this same structure but simply removing Meteor.bindEnvironmentprints again to the console but doesn't update.
Am I doing something wrong?
Related
I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.
I'm developing a node js rest server and having an issue with my Schema queries. When I hit my end points I get the error TypeError: user.find is not a function
The following is my user.js file
var {mongoose} = require('../../dbcore/mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User',new Schema( {
basicId: Schema.ObjectId,
activePurchaseIDs: {
type: [Schema.ObjectId],
default: []
},
activeOrderIDs: {
type: [Schema.ObjectId],
default: []
},
paymentOptionIDs: {
type: [Schema.ObjectId],
default: []
},
addressIDs: {
type: [Schema.ObjectId],
default: []
},
interestIDs: {
type: [Schema.ObjectId],
default: []
}
}));
and this is where it's imported/required.
var URLS = require('./urls');
var User = require('../schemas/user/user');
function init(app,mongoose) {
app.get(URLS.USERS_URL,(req,res)=>{
var user = new User({});
user.find().then((users)=>{
res.send({users});
},(err)=>{
res.status(400).send(err);
});
});
}
module.exports = init;
I was following a tutorial while writing this code and I was expecting it to work as I followed the tutorial step by step.
When you call var user = new User({}) you are creating a new MongoDB document based on the User model and assigning it to var user.
A single user document does not have a find() function, but your User model does.
var user = new User({});
User.find().then(...);
app.get(URLS.USERS_URL, async (req,res)=>{
const userList = await User.find();
if(!userList) {
res.status(500).json({success: false});
}
res.send(userList);
});
Your call to the database needs to look like this:
User.find().then((users)=>{
res.send({users});
}).catch((err)=>{
res.status(400).send(err);
});
You should call it directly on the module, because mongoose will handle creation implicitly and creating a new object isn't neccesary.
I'm not sure if your schema is correctly defined, but I'm not going to say your tutorial is wrong on that. You should go into mongo shell and check if the schema was created to verify it was designed correctly.
In my case, I wrote wrong this so check your file exports module.exports = XYZ format.
PS:- I wrote like this exports.module = XYZ
I am attempting to update an entity in my datastore kind using sample code from here https://cloud.google.com/datastore/docs/reference/libraries. The actual code is something like this:
/ Imports the Google Cloud client library
const Datastore = require('#google-cloud/datastore');
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
});
// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);
// Prepares the new entity
const task = {
key: taskKey,
data: {
description: 'Buy milk',
},
};
// Saves the entity
datastore
.save(task)
.then(() => {
console.log(`Saved ${task.key.name}: ${task.data.description}`);
})
.catch(err => {
console.error('ERROR:', err);
});
I tried to create a new entity using this code. But when I ran this code and checked the datastore console, there were no entitites created.Also, I am unable to update an existing entity. What could be the reason for this?
I am writing the code in Google Cloud Functions.This is the log when I run this function:
{
insertId: "-ft02akcfpq"
logName: "projects/test-66600/logs/cloudaudit.googleapis.com%2Factivity"
operation: {…}
protoPayload: {…}
receiveTimestamp: "2018-06-15T09:36:13.760751077Z"
resource: {…}
severity: "NOTICE"
timestamp: "2018-06-15T09:36:13.436Z"
}
{
insertId: "000000-ab6c5ad2-3371-429a-bea2-87f8f7e36bcf"
labels: {…}
logName: "projects/test-66600/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2018-06-15T09:36:17.865654673Z"
resource: {…}
severity: "ERROR"
textPayload: "Warning, estimating Firebase Config based on GCLOUD_PROJECT. Intializing firebase-admin may fail"
timestamp: "2018-06-15T09:36:09.434Z"
}
I have tried the same code and it works for me. However, I have noticed that there was a delay before the entities appeared in Datastore. In order to update and overwrite existing entities, use .upsert(task) instead of .save(task) (link to GCP documentation). You can also use .insert(task) instead of .save(task) to store new entities.
Also check that the project id is correct and that you are inspecting the entities for the right kind.
I'm new to Backbone and Firebase. I'm using Backfire, have a collection:
var UsersCollection = Backbone.Firebase.Collection.extend({
model: UserModel,
firebase: new Firebase( "https://xxxxxx.firebaseio.com/users" ),
});
The model itself is not tied to Firebase (was getting "Invalid Firebase reference created" error):
var UserModel = Backbone.Model.extend({
defaults: function() {
return {
email: "example#example.com"
};
}
});
In my View, I instantiate the collection, and I get the data okay, and I can add new models to the collection, as follows:
this.allUsers = new UsersCollection();
...
this.allUsers.add( userData );
Works great, new user records appear on Firebase. However, let's say I now want to grab a given user's model and update its data:
var userRecord = this.allUsers.findWhere( {email: email} );
userRecord.set( {age: age} );
This updates the model locally but the changed model is NOT getting synced to Firebase. I tried userRecord.save(); afterwards but it triggers a "circular reference" error. Per the docs, set() should do it bur clearly something is off :(
The userRecord variable comes back as undefined in this case because the allUsers collection hasn't been populated with data yet. The data is still being downloaded to Firebase when you are calling .findWhere().
To avoid this, you can listen to the sync event and do all of your actions from there.
JSBin example.
allUsers.on('sync', function(collection) {
// collection is allUsers
var userRecord = collection.findWhere( {email: 'david#email.com'} );
userRecord.on('change', function(model) {
console.log('changed', model);
});
userRecord.set( {age:4} );
});
You'll want to ensure your collections are populated before you process any actions on them. The sync event is the recommended way to do this.
I'm using Backbone.js to route profile views so I can view data belonging to /user, and that part works fine. I'm able to generate an _id based on the username and pass it into the server publish function, which logs it. However, when I log the results back to the client in the subscribe function, my result looks like this:
Object {stop: function, ready: function}
//Client Side
Template.userquery.userproject = function() {
var query = Session.get('userquery');
var user = Meteor.users.findOne({username: query});
if (user) {
console.log(user._id); //(works)
campaigns = Meteor.subscribe('userquery', user._id, function() {
console.log('ready'); //(works)
});
console.log(campaigns); //(returns Object {stop: function, ready: function})
return campaigns;
}
}
//Server Side
Meteor.publish('userquery', function(userid) {
console.log('break');
console.log(userid); //(I get userid in Terminal)
var campaigns = Campaigns.find({owner: userid}, {fields: {owner: 1, name: 1}});
if (campaigns) {
console.log(campaigns);
return campaigns;
}
});
Am I missing something in this function? I have autopublish turned off because it was generating my search twice.
Meteor.subscribe, according to the docs, "Returns a handle that provides stop() and ready() methods." So the behaviour you're seeing is intended.