db.collection.update() throws 'undefined is not a function' - meteor

I have this server side method (Meteor method) that successfully finds a document by the ID that it is passed, but when I go to issue a mongo .update(), I get an internal server error (500).
setToggle: function(detailId){
var checked_detail = detailsCollection.findOne({_id: detailId});
checked_detail.update({$set: {checkboxStatus: 'toggle'}});
}
Here is where I initially call the method on the client to create the document:
'submit form': function(ev){
ev.preventDefault();
var detailFormData = {
detail: $(ev.target).find('[name = detail]').val(),
parentId: $(ev.target).find('[name = parentId]').val(),
checkboxStatus: ''
}
Meteor.call('addDetail', detailFormData);
}
And here is that server insert method, so you can see the model:
addDetail: function(detailFormData){
if(! Meteor.userId()){
throw new Meteor.Error('not-authorized');
}
detailsCollection.insert({
detail: detailFormData.detail,
parentId: detailFormData.parentId,
checkboxStatus: detailFormData.checkboxStatus
});
}

Your update syntax is wrong : you're retrieving the Mongo document and then trying to call the update operation on the resulting plain JS object instead of calling the method on the collection itself.
Rewrite your code like this :
setToggle: function(detailId){
detailsCollection.update(detailId,{
$set: {checkboxStatus: 'toggle'}
});
}
The Mongo Collection update syntax takes two (mandatory) parameters :
a Mongo selector to identify which documents in the collection should be updated (on the client using minimongo you're only allowed to modify documents by _id).
a Mongo modifier object to specify how the matching documents should be modified.
https://docs.meteor.com/#/full/update

Related

Meteor audit-argument-checks

I have a Meteor project where I'm using audit-argument-check. I'm getting an error message
Error: Did not check() all arguments during publisher 'document
I'm know this is related the audit-argument-check not being able to check all arguments. But as far as I'm concerned, I checked all of them. Concrete, I have defined a collection 'documents' and attached a SimpleSchema. As part of iron-router, I have the following:
Router.route('customerDocumentShow', {
template: 'customerDocumentShow',
path: 'customer/documents/:_id',
waitOn: function () {
return Meteor.subscribe('document', this.params._id);
},
data: function () {
return Documents.findOne(this.params._id);
}
});
So I'm passing only the documentId (this.params._id). On the server, I have defined a method:
Meteor.methods({
documentsReadMethod: function(documentId){
check(documentId, String);
var documentItem = Document.findOne(argument);
if (!documentItem) {
throw new Meteor.Error(500, 'Error 500: Not Found', 'No documents found.');
}
return documentItem;
}
});
So I'm checking to documentId in the server method. So not sure why I'm getting this error message.
Note: One thing I'm not entirely sure about though is how I need to call this method (right now, it's documentsReadMethod_. I'm not explicitly calling (on the client):
Meteor.call(documentsReadMethod, this.params_id);
as I'm using autoform, collection2 and simpleschema. I've been spending the entire weekend, but have no clue. Any idea's ?
Note: the code is on github: https://github.com/wymedia/meteor-starter-base
The problem is in the publish. You didn't check the id here:
https://github.com/wymedia/meteor-starter-base/blob/master/server/publications/documents.js#L16
Just add check(id, String); line 16 and it should work.
I have the same problem with another tuto !
Answer found at check is not defined in meteor.js : since Meteor v1.2, you have to add this package:
$ meteor add check

Implementing a simple search with Meteor and Iron Router

In the next phase of my Meteor journey (read: learning the ropes!), I'd like to implement a simple search based on user inputed values, then redirect to a route specific to the record returned from the server.
At the moment, I'm picking up the inputed values via this code:
Template.home.events 'submit form': (event, template) ->
event.preventDefault()
console.log 'form submitted!'
countryFirst = event.target.firstCountrySearch.value
countrySecond = event.target.secondCountrySearch.value
Session.set 'countryPairSearchInputs', [countryFirst, countrySecond]
countryPairSearchInputs = Session.get 'countryPairSearchInputs'
console.log(countryPairSearchInputs)
return Router.go('explore')
Happily, the console log returns the desired countryPairSearchInputs variable - an array of two ids. In my routes.coffee file I then have the following:
#route "explore",
path: "/explore/:_id"
waitOn: ->
Meteor.subscribe 'countryPairsSearch'
On the server side, I have:
Meteor.publish 'countryPairsSearch', getCountryPairsSearch
And finally, I have a search.coffee file in my /lib directory that defines the getCountryPairsSearch function:
#getCountryPairsSearch = ->
CountryPairs.findOne $and: [
{ country_a_id: $in: Session.get('countryPairSearchInputs') }
{ country_b_id: $in: Session.get('countryPairSearchInputs') }
]
With regards to the search function itself, I have a CountryPairs collection where each record has two ids (country_a_id and country_b_id) - the aim here is to allow users to input two countries, with the corresponding CountryPair then being returning.
I'm currently struggling to tie all the pieces together - the console output on searching is currently:
Uncaught Error: Missing required parameters on path "/explore/:_id". The missing params are: ["_id"]. The params object passed in was: undefined.
Any help would be greatly appreciated - as you can probably tell I'm new to Meteor and am still getting used to the pub/sub methodology!
Edited: mixed up client/server for the publish method when I first posted - the danger of late-night posting!
First, seems you're expecting an :id parameter on your 'explore' route.
If I understand you're case, you're not expecting any params here, so you can just delete ':id' from your route:
#route "explore",
path: "/explore/"
waitOn: ->
Meteor.subscribe 'countryPairsSearch'
or either add a params to your Router.go call:
Router.go('explore', {_id: yourIdVar});
Secondly, you're trying to use a client function: Session.get() server-side. Try to update the publication using a parameter ; or using a method.call.
client-side
Meteor.subscribe 'countryPairsSearch' countryA countryB
not sure about the coffeescript syntax, check http://docs.meteor.com/#/full/meteor_subscribe
and server-side
#getCountryPairsSearch = (countryA, countryB) ->
CountryPairs.findOne $and: [
{ country_a_id: $in: countryA }
{ country_b_id: $in: countryB }
]

Update Mongo on the client using document ID, but limiting search with another field

When updating a document which contains an array of objects, I have this function:
Template.editCompetition.events = {
'click button.promote': function() {
Competitions.update({_id: Session.get('competition_id'), 'players.user_id': this.user_id}, {$set: {'players.$.supervisor': true}});
},
};
I am seeing the error:
Uncaught Error: Not permitted. Untrusted code may only update documents by ID.
My document looks like this:
{
_id: 'aaaabbbbb',
title: 'ccccdddddd',
players: [
{
username: 'wwwww',
user_id: 'xxxxx',
supervisor: false
},
{
username: 'yyyyy',
user_id: 'zzzzz',
supervisor: false
}]
}
Isn't my query updating the document by the ID, but also searching for that array position to use the .$ notation.
How can I achieve this without using a method, which seems a bit hacky...?
You are also trying to use the player.user_id as second parameter for update query
Other option you can have to use Meteor.method.
Move Collection update code to Meteor server side method and call it from client side
On Server side,
Meteor.methods({
`update_players`: function(competition_id){
user_id = this.userId
Competitions.update({_id: competition_id, 'players.user_id': user_id}, {$set: {'players.$.supervisor': true}});
}
})
In in above code, understand use of how we fetched current userId with this.userId
and now from your click handler call this meteror method
Meteor.call('update_players')
Hope this helps

Meteor Blaze error with Template Helper

Most of my template helpers result in blaze errors and I'm not sure why. What makes them more strange is that they do not block rendering or events from the templates at all, in fact, the app works fine.
The main issue is a messy, messy, console. An example of this is below:
Template.templatename.helpers({
adminhelper: function(){
var theUser = Meteor.user(),
theUserId = theUser['_id'];
if(theUserId == "XXX"){
return true;
}
}
});
Just one way of checking which user is an admin user. This results in:
Exception in template helper: TypeError: Cannot read property '_id' of undefined
at Object.Template.templatename.helpers.adminhelper (http://localhost:3000/client/lib/helpers.js?37db222f849959237e4f36abdd8eba8f4157bd32:5:23)
at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2693:16
at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1602:16
at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?3c496d2950151d744a8574297b46d2763a123bdf:169:18)
at Template.manage.Blaze.If.HTML.HEADER.HTML.DIV.class (http://localhost:3000/client/views/template.templatename.js?868248757c652b031f64adad0edec9e2a276b925:6:22)
at null.<anonymous> (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2454:44)
at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1795:16
at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2029:12)
at viewAutorun (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1794:18)
at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:288:36)
Interestingly, client/views/template.templatename.js does not exist. I put all helpers in a helpers.js file, and all events in an events.js file.
For my route I have
Router.route('/theurl',function(){
this.render('templatename');
},{
waitOn: function(){
return Meteor.user();
}
});
What can I do to avoid these issues in the future?
Just use a guard to check for the existence of Meteor.user() before extracting the _id. Waiting on Meteor.user() in the route doesn't work, as waitOn requires a subscription. Alternatively you can just do this:
Template.templatename.helpers({
adminhelper: function() {
return Meteor.userId() === 'XXX';
}
});
An even better solution is to use the roles package.

Meteor Iron-Router: why isn't this routing setup (with waitOn and data functions) working correctly?

Using Iron-Router 1.0.3 and Meteor 1.0.
I have this route defined:
Router.route('audit', {
path: '/audit/:audit_id/',
template: 'audit',
data: function() {
audit = Audits.findOne({_id: this.params.audit_id});
lineitems = LineItems.find(JSON.parse(audit.query));
return {
audit: audit,
lineitems: lineitems
}
},
waitOn: function () {
return [
Meteor.subscribe('audits'),
Meteor.subscribe('lineitems', this.params.audit_id),
]
}
});
Objects in the Audits collection have the following structure:
{
_id: 'timestamped-id-that-I-generate',
name: 'some name',
query: JSON.stringify({'$and': [list of query conditions here]})
}
When I go to this route I get the following error in my console:
Uncaught TypeError: Cannot read property 'query' of undefined
But if I go to my browser console, I can examine the Audits collections and I see that the Audit object with the appropriate _id and query exists as expected.
Incidentally, the publish method for the lineitems on the server side will simply look up the same audit object and publish the line items that match it's query.
(I have to serialize the query back and forth via JSON because otherwise the query object would contain field names that violate MongoDB regulations.)
As of this writing, Iron Router's data hook may run multiple times when a route is evaluated. You can assume it will run once before the subscriptions are ready, and again afterward. Because it will run prior to your subscriptions being ready, you need to assume that Audits.findOne will return undefined at least once. You have two choices:
Check for this.ready() in your data hook:
data: function() {
if (this.ready()) {
audit = Audits.findOne({_id: this.params.audit_id});
lineitems = LineItems.find(JSON.parse(audit.query));
return {audit: audit, lineitems: lineitems};
}
}
Use a guard:
data: function() {
audit = Audits.findOne({_id: this.params.audit_id});
if (audit && audit.query) {
lineitems = LineItems.find(JSON.parse(audit.query));
return {audit: audit, lineitems: lineitems};
}
}
A combination of the two may actually be appropriate if: (a) you don't have any audits, or (b) not all audits have a query.

Resources