What am I doing wrong when manipulating data in Meteor/MongoDB? - mongodb

I have this helper
myClub: function(){
var currentUserId = Meteor.userId();
var user = Meteor.users.findOne({_id: currentUserId});
return user;
}
I want it to return user.role
Here is my user in MongoDB
{
"_id" : "RdirmrLG3t8qBk4js",
"createdAt" : ISODate("2016-04-17T19:40:56.877Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$cPe92XR9DT238bH/RanYEu.J6K2ImvAEbWOcVq6j9luI0BH08Qdly"
},
"resume" : {
"loginTokens" : [
{
"when" : ISODate("2016-04-17T19:51:49.474Z"),
"hashedToken" : "uVKUj/7JEkkOuizXhjl212Z38E47HXCex+D4zRikQ1k="
}
]
}
},
"username" : "worker",
"role" : "worker",
"club" : "hzSKAJfPXo7hSpTYS"
}
The code above works just fine. So it finds the current user and outputs info about it. But when I change user to user.role I get the following errormessage.
TypeError: Cannot read property 'role' of undefined
at Object.myClub
How can it be undefined? Is my syntax incorrect?

Template helpers are reactive, which means they update themselves as the app state changes or new data appears. In your case, the helper is called immediately when the template is rendered and before the Meteor.users collection is filled. Therefore, the .findOne() method returns undefined. It will be corrected in the second pass after new data arrives.
The simple fix here is to check whether the data is present inside the helper:
myClub: function(){
var currenUserId = Meteor.userId();
var user = Meteor.users.findOne({_id: currenUserId});
if(!user) return 'NO DATA';
return user.role;
},
In real life you'll probably want to wait for the basic data to be loaded before you render the template. That is usually done on the controller level.

Try:
myClub: function(){
return Meteor.user() && Meteor.user().role;
}
This is shorthand for return the role if there's a user.
As far as the role field not showing up, make sure that you are publishing that key from the server and subscribing to it. For example:
Meteor.publish('me',function(){
return Meteor.users.find(this.userId,{fields: {role: 1, username: 1, profile: 1, emails: 1}});
});
And on the client:
var me = Meteor.subscribe('me');
if ( me.ready() ) console.log("Ta-da! The role is: "+Meteor.user().role);

make sure that you subscribed to all data you need.
By the way, you can try following:
role: function(){ return (Meteor.user() || {}).role; }
Cheers

Related

How MongoClient::save(...) might change the _id field of document parameter

I have a class User that embeds a JsonObject to represent the user's fields. This class looks like that:
class User {
private JsonObject data;
public User(...) {
data = new JsonObject();
data.put("...", ...).put(..., ...);
}
public String getID() { return data.getString("_id"); }
// more getters, setters
// DB access methods
public static userSave(MongoClient mc, User user){
// some house keeping
mc.save("users", user.jsonObject(), ar -> {
if(ar.succeeded()) { ... } else { ... }
});
}
}
I've just spent more than half a day trying to figure out why a call to user.getID() sometimes produced the following error: ClassCastException: class io.vertx.core.json.JsonObject cannot be cast to class java.lang.CharSequence. I narrowed down to the userSave() method and more specifically to MongoClient::save() which actually produces a side effect which transforms the data._id from something like
"_id" : "5ceb8ebb9790855fad9be2fc"
into something like
"_id" : {
"$oid" : "5ceb8ebb9790855fad9be2fc"
}
This is confirmed by the vertx documentation which states that "This operation might change _id field of document parameter". This actually is also true for other write methods like inserts.
I came with two solutions and few questions about doing the save() properly while keeping the _id field up to date.
S1 One way to achieve that is to save a copy of the Json Object rather than the object itself, in other words : mc.save("users", user.jsonObject().copy(), ar -> {...});. This might be expensive on the long run.
S2 An other way is to "remember" _id and then to reinsert it into the data object in the if(ar.succeeded()) {data.put("_id", oidValue); ...} section. But as we are asynchronous, I don't think that the interval between save() and the data.put(...) is atomic ?
Q1: Solution S1 make the assumption that the ID doesn't change, i.e., the string 5ceb8ebb9790855fad9be2fc will not change. Do we have a warranty about this ?
Q2: What is the right way to implement the saveUser() properly ?
EDIT: The configuration JSON object user for the creation of the MongoClient is as follows (in case there is something wrong) :
"main_pool" : {
"pool_name" : "mongodb",
"host" : "localhost",
"port" : 27017,
"db_name" : "appdb",
"username" : "xxxxxxxxx",
"password" : "xxxxxxxxx",
"authSource" : "admin",
"maxPoolSize" : 5,
"minPoolSize" : 1,
"useObjectId" : true,
"connectTimeoutMS" : 5000,
"socketTimeoutMS" : 5000,
"serverSelectionTimeoutMS" : 5000
}

Relay/Mongodb Error - Cannot Read Property of Undefined

I have this test relay-starter-kit project with an autocomplete search form that renders quotes to the browser. When I use the search form, I get an error in the browser saying "app.js:8284 Uncaught TypeError: Cannot read property 'edges' of undefined". I cant understand why its populating the search fields the first time but not on typing in the search form. Of note, if you hard code the searchTerm variable, it will render the search results. In other words, It can read the edges when its hard coded. Any guidance on this would be great. Thanks.
The schema is here
This is the component that the valid graphql query for the search term wont render to.
import React from 'react';
import Relay from 'react-relay';
import { debounce } from 'lodash';
import SearchForm from '../search-form';
import Quote from '../quote';
class App extends React.Component {
constructor(props) {
super(props)
this.search = debounce(this.search.bind(this), 300)
}
search(searchTerm) {
this.props.relay.setVariables({ searchTerm });
}
render() {
return (
<div className="quotes-library">
<SearchForm searchAction={this.search} />
<div className="quotes-list">
{this.props.viewer.quotes.edges.map(edge =>
<Quote key={edge.node.id} quote={edge.node} />
)}
</div>
</div>
)
}
}
export default Relay.createContainer(App, {
initialVariables: {
searchTerm: '',
},
fragments: {
viewer: () => Relay.QL`
fragment on User {
quotes(first:100, searchTerm: $searchTerm) {
edges {
node {
id
${Quote.getFragment('quote')}
}
}
}
}
`,
},
});
Update: This is the query as shown in Chrome DevTools network tab. Note the 'p' input to the search form is being queried.
query App_ViewerRelayQL($id_0:ID!) {
node(id:$id_0) {
...F2
}
}
fragment F0 on Quote {
id,
likesCount
}
fragment F1 on Quote {
text,
author,
id,
...F0
}
fragment F2 on User {
_quotes3UfnML:quotes(first:100,searchTerm:"pri") {
edges {
node {
id,
...F1
},
cursor
},
pageInfo {
hasNextPage,
hasPreviousPage
}
},
id
}
Adding console.log to render() shows the searchTerm input:
app.js:17
{
"viewer": {
"__dataID__": "VXNlcjox",
"__status__": 4
},
"relay": {
"pendingVariables": null,
"route": {
"name": "AppHomeRoute",
"params": {},
"queries": {}
},
"variables": {
"searchTerm": "pri"
}
}
}
The following error occurs at line 24 in app.js, which is {this.props.library.quotes.edges.map(edge =>
<Quote key={edge.node.id} quote={edge.node} />
)}:
app.js:8285 Uncaught TypeError: Cannot read property 'edges' of undefined
at App.render (app.js:8285)
at app.js:43197
at measureLifeCyclePerf (app.js:42476)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (app.js:43196)
at ReactCompositeComponentWrapper._renderValidatedComponent (app.js:43223)
at ReactCompositeComponentWrapper._updateRenderedComponent (app.js:43147)
at ReactCompositeComponentWrapper._performComponentUpdate (app.js:43125)
at ReactCompositeComponentWrapper.updateComponent (app.js:43046)
at ReactCompositeComponentWrapper.receiveComponent (app.js:42948)
at Object.receiveComponent (app.js:35341)
UPDATE 2:
So check this out. I'm doing something wrong with my { ObjectID }. I pulled a user and quote from the db and there is an '_id' but no 'id' property on the object. This is the output:
> db.users.find({})
{ "_id" : ObjectId("586253169465191cb812066c"), "name" : "me", "id" : ObjectId("586253169465191cb812066c"), "errors" : [ ] }
> db.quotes.find({})
{ "_id" : ObjectId("586693333ff93f3581c0ca05"), "text" : "Hi Prisc", "author" : "H. Jackson Brown", "likesCount" : 24 }
{ "_id" : ObjectId("586693333ff93f3581c0ca06"), "text" : "If opportunity doesn't knock, build a door", "author" : "Milton Berle", "likesCount" : 2 }
{ "_id" : ObjectId("586693333ff93f3581c0ca07"), "text" : "Try to be a rainbow in...", "author" : "Maya Angelou" }
If I log the id from the globalIdFetcher(), the logged id for the Jackson Brown Quote object show two id's as expected but they are both the same and different from the one in the db. Output in console is:
{
"viewer": {
"__dataID__": "VXNlcjo=",
"quotes": {
"__dataID__": "client:6068631311_first(100),searchTerm()",
"edges": [
{
"__dataID__": "client:client:6068631311:UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
"node": {
"__dataID__": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
"id": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
"__fragments__": {
"1::client": [
{
"showLikes": false
}
]
}
}
},
Any ideas on fixing this syntax?
It's very difficult to solve the problem with the information provided in question. As you requested guidance, here's my suggestions :)
I cant understand why its populating the search fields the first time but not on typing in the search form.
Because Relay fetches the result for the initial value of searchTerm, which is an empty string in your case. You have to deal with this case on the server side (by checking the input searchTerm) and client side (by checking if the current value of searchTerm is empty, for example).
When you type in search form, search() isn't called and searchTerm is not updated. Check SearchForm component.
When I use the search form, I get an error in the browser saying "app.js:8284 Uncaught TypeError: Cannot read property 'edges' of undefined".
Start debugging what the server side returns for quotes field under viewer GraphQL object type. What's the output of db.collection('quotes').find(findParams).toArray() in your schema? In addition, put a console.log(JSON.stringify(this.props, null, 4)) in render() function of App class. Check what you see. You can also inspect the HTTP request and response on the Chrome DevTools Network tab. Filter by graphql.
Solution was to take the Quote type out of the nodeInterface so only running the top level object through the nodeInterface, let relay generate the id for the objectId from the GraphQLID or fromGlobalId as defined in the individual itemType.

How should you query a collection via nested arrays in mongodb (Meteor)?

I'm dont think that this is a Meteor specific question, but rather around mongo and building mongo queries.
If I have the following structure,
{
username : someName,
contacts : [
{
userid : asdfae33rtqqxxx,
name : contactName,
status : friend
}
{
userid : asdfae33rtqqxxx,
name : anotherName,
status : pending
}
{
userid : asdfae33rtqqxxx,
name : contactName,
status : blocked
}
]
}
How could I pass in values from this array into a query against the users collection, to a) get the users in this array, or b) get all users in this array from the users collection with a particular status.
If this is not possible, how should I adjust my schema in order to make these sorts of queries possible?
This function will return a Meteor.users cursor based on an array of contacts and an optionally required status:
var usersByContacts = function(contacts, requiredStatus) {
var userIds = _.chain(contacts)
.map(function(c) {
if (requiredStatus) {
if (c.status === requiredStatus)
return c.userid;
} else {
return c.userid;
}
})
.compact()
.value();
return Meteor.users.find({_id: {$in: userIds}});
};
You can use it like this:
var users1 = usersByContacts(thing.contacts);
var users2 = usersByContacts(thing.contacts, 'pending');
This assumes thing has the schema referenced in your question. Also note that if you find this is a common pattern in your code, you should consider turning usersByContacts into a transform.

Meteor queries not working with Meteor.Collection.ObjectID

I'm having a lot of trouble getting query results for certain collections in Meteor.
I have set
idGeneration : 'MONGO'
in the collection definitions, and in the mongo shell these collections look like this :
the document i want, call it documentW (from CollectionA) = {
"_id" : ObjectId("7032d38d35306f4472844be1"),
"product_id" : ObjectId("4660a328bd55247e395edd23"),
"producer_id" : ObjectId("a5ad120fa9e5ce31926112a7") }
documentX (from collection "Products") = {
_id : ObjectId("4660a328bd55247e395edd23")
}
documentY (from collection "Producers") = {
_id : ObjectId("a5ad120fa9e5ce31926112a7")
}
If i run a query like this in Meteor
CollectionA.findOne({ product_id : documentX._id, producer_id : documentY._id})
I'm expecting to get my documentW back... but I get nothing.
When I run this query in the mongo shell
db.collectiona.find({ product_id : ObjectId("4660a328bd55247e395edd23"), producer_id :
ObjectId("a5ad120fa9e5ce31926112a7") })
I get my documentW back no problem.
Of course in Meteor if I call
console.log(documentX._id)
I get this
{ _str : "4660a328bd55247e395edd23" }
Anyone have any ideas what is going on here ? I have tried all kinds of things like
Meteor.Collection.ObjectID(documentX._id._str)
but the search still returns empty...
Running the latest 0.7.0.1 version of Meteor...
I don't know if this answers your question, but I can't put this code in a comment. This code is working for me, trying to follow what I believe you are trying to do:
Products = new Meteor.Collection("products", {
idGeneration: "MONGO"
});
Producers = new Meteor.Collection("producers", {
idGeneration: "MONGO"
});
CollectionA = new Meteor.Collection("a", {
idGeneration: "MONGO"
});
Products.insert({
foo: "bar"
});
Producers.insert({
fizz: "buzz"
});
var documentX = Products.findOne();
var documentY = Producers.findOne();
CollectionA.insert({
product_id: documentX._id,
producer_id: documentY._id
});
var documentW = CollectionA.findOne({
product_id: documentX._id,
producer_id: documentY._id
});
console.log(documentW); // This properly logs the newly created document
This is on 0.7.0.1. Do you see anything in your code that diverges from this?

How to pass model name to angularJS restful api

I am new to AngularJS, but have used Backbone for a while now.
I want to create a reusable restful api that I can pass the model name to so that I can use it for different models.
At the moment I have:
angular.module('healthplanApiServices', ['ngResource'])
.factory('Api', function($resource) {
return $resource(base_url + 'api/:object/:id', {
id : '#id', object : 'actions'
}, {
query : {
method : 'GET',
isArray : true,
callback : "JSON_CALLBACK"
},
save : {
method : '#id' ? 'PUT' : 'POST',
isArray : true,
callback : "JSON_CALLBACK"
}
});
});
... which sets the model as 'actions'. Then in my controller I use:
// get the collection
Api.query(function(r) {
$scope.actions = r;
});
$scope.toggleDone = function(a) {
a.done = !a.done;
//save an item
Api.save(a);
}
That's all fine, but how do I pass the model name ('actions' in this case) for each model type: e.g., instead of putting it in the factory function like so:
id : '#id', object : 'actions'
... but rather something more like:
var ActionApi = Api.setObject('actions');
ActionApi.query(function(r) {
$scope.actions = r;
});
UPDATE:
I just figured out a way. It may not be the best, but it does work. Any other suggestions would be welcome!
Just add the 'object' attribute to the model:
Api.query({object: 'actions'}, function(r) {
$scope.actions = r;
angular.forEach($scope.actions, function(a) {
a.object = 'actions' });
});
Api.save(a);// also works
You may want to try https://github.com/klederson/ModelCore ( ModelCore )
Its easy to model and structure and of course ... to use.
model.$find({ filter : "John" },{},true); //to find all with query parameters
model.$get(1); //to retreive the user with id 1
model.$save()
model.$deelte();
And so on.. checkout the documentation