I'm building a Meteor application and want users to be able to update/set their name. I've got the code set up, and everything seems to be working except that it mysteriously fails on the update. Here's my code:
Template
<template name="_editName">
{{#ionModal focusFirstInput=true customTemplate=true}}
<form id="updateName">
<div class="bar bar-header bar-stable">
<button data-dismiss="modal" type="button" class="button button-clear button-assertive">Cancel</button>
<h2 class="title">Update your name</h2>
<button type="submit" class="button button-positive button-clear">Save</button>
</div>
<div class="content has-header overflow-scroll list">
<label class="item item-input">
<input type="text" id="firstName" placeholder="Given Name">
</label>
<label class="item item-input">
<input type="text" id="lastName" placeholder="Surname">
</label>
</div>
</form>
{{/ionModal}}
</template>
Client-side code
Template._editName.events({
'submit #updateName': function(event, template) {
event.preventDefault();
console.log('Submitted');
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
Meteor.call('editName', firstName, lastName, function(error) {
if (error) {
throw new Error(error.reason);
} else {
Router.go('profile');
}
});
IonModal.close();
IonKeyboard.close();
}
});
Server-side code
Meteor.methods({
'editName': function(firstName, lastName) {
console.log(firstName); // returns expected value
console.log(lastName); // returns expected value
Meteor.users.update({_id: this.userId}, {$set: {
'profile.firstName': firstName,
'profile.lastName': lastName
}});
Meteor.users.findOne({_id: this.userId}, {fields: {
'profile.firstName': 1, _id: 0}}); // returns undefined
}
});
Everything works as it should: On submit, the function gets the field values, calls the method on the server, successfully passing the field values. The update seems to be working as no error is thrown. However, the 'profile.firstName' returns undefined and does not show up in my template.
I'm using the accounts-base package and aldeed:collection2. I have the following schema set up:
Schema.UserProfile = new SimpleSchema({
firstName: {
type: String,
regEx: /^[a-zA-Z-]{2,25}$/,
optional: true
},
lastName: {
type: String,
regEx: /^[a-zA-Z]{2,25}$/,
optional: true
}
});
I have absolutely no idea what's going wrong and would appreciate every help!
I've checked your code and I found multiple issues which need your attention.
Please get the fixed project from here and follow the instructions to get and run it.
The main issues were:
In your collection's schema definition you first specified the UserSchema and referenced the UserProfile schema. Since the UserProfile didn't exist by the time you referenced it, the code was failing silently. Maybe you address this with the package owner for a better error and reference check handling.
You should definitely read upon meteor's databinding since under the profile.html templates you did quite a few mistakes
Initialize your profile schema on user creation:
Accounts.onCreateUser(function(options, user) {
// We're enforcing at least a profile skeleton object to avoid needing to check
// for its existence later.
// this file should reside on Server (e.g. [root]/server/accounts.js)
profile = {
firstName: '',
lastName: '',
birthday: '',
sex: '',
grade: '',
country: '',
hostel: '',
house:''
}
user.profile = profile;
return user;
});
Expose the published fields for your custom profile
Meteor.publish('userProfile', function() {
if(!this.userId) {
return null
} else {
return Meteor.users.find({_id: this.userId}, {
fields: {
username: 1,
'profile.firstName': 1,
'profile.birthday': 1,
'profile.sex': 1,
'profile.grade': 1,
'profile.country': 1,
'profile.hostel': 1,
'profile.house': 1
}
});
}
General meteor / JS coding standard issues which you will want to review
There are also other things you would like to check like, variable scoping, unit testing, performance etc. before you go to production with this.
As a general rule (from my experience at least) I would always start at a bare minimum and avoiding to use complex packages without a solid foundation of the framework at hand. This will save you a lot of debugging and frustration like this in the future :).
Please accept this answer as soon as you have verified it so I can delete it again from my github account.
Good luck.
Please see my working example code below for you reference:
User detail template markup
{{#with currUser}}
<form class="edit-todo" id="edit-user">
Username:
<input type="text" name="username" value="{{profile.name}}" />
Firstname:
<input type="text" name="firstname" value="{{profile.firstname}}" />
Lastname:
<input type="text" name="lastname" value="{{profile.lastname}}" />
<button type="submit" style="width: 100px;height:50px">Save user</button>
</form>
{{/with}}
User detail template code
Template.UsersDetail.events({
'submit form#edit-user': function(e, tmpl) {
e.preventDefault();
var firstname = tmpl.find('input[name=firstname]').value;
var lastname = tmpl.find('input[name=lastname]').value;
var userId = Meteor.userId();
Meteor.call('editName', userId, firstname, lastname, function(error) {
if (error) {
throw new Error(error.reason);
} else {
Router.go('users.detail', {
_id: userId
});
}
});
}
});
Template.UsersDetail.helpers({
currUser: function() {
return Meteor.users.findOne({
_id: Meteor.userId()
});
}
});
Server method for name updates
/*****************************************************************************/
/* Server Only Methods */
Meteor.methods({
'editName': function(userId, firstName, lastName) {
Meteor.users.update({_id: userId}, {$set: {
'profile.firstname': firstName,
'profile.lastname': lastName
}});
console.log(Meteor.users.findOne({_id: this.userId}).profile.lastname);// returns the proper name
}
});
Related
I am working through this Meteor tutorial and I have updated imports/ui/task.html to only show the tasks to the user who created them as follows:
<template name="task">
{{#if isOwner}}
<li class="{{#if checked}}checked{{/if}} {{#if private}}private{{/if}}">
<button class="delete">×</button>
<input type="checkbox" checked="{{checked}}" class="toggle-checked" />
<span class="text">{{text}}</span>
</li>
{{/if}}
</template>
However, I still have the incomplete count showing tasks by all users and I want to change it to just the user who is logged in. This is the part of imports/ui/body.js that I think needs to be changed.
Template.body.helpers({
tasks() {
const instance = Template.instance();
if (instance.state.get('hideCompleted')) {
// If hide completed is checked, filter tasks
return Tasks.find({ checked: { $ne: true } }, { sort: { createdAt: -1 } });
}
// Otherwise, return all of the tasks
// Show newest tasks at the top. This is the meat of the thing!
return Tasks.find({}, { sort: { createdAt: -1 } });
},
incompleteCount() {
return Tasks.find({ checked: { $ne: true } }).count();
},
});
You only need to filter on ownerId which is used in this tutorial to associate a task with a user.
incompleteCount() {
return Tasks.find({ ownerId: Meteor.userId(), checked: { $ne: true } }).count();
},
Note that when you use multiple criteria like this they are implicitly ANDed.
I have a Vue component that will display data depending on what the user previously clicked on in a previous component. When they originally click, I set the 'current' index. Then when they get to the next page, I have a getter that will look in the data array and return the 'current' data.
The component they are redirected to is a form that they can edit. I would like to be able to have the 'current' data be pre-populated. NOT as a placeholder but as the actual value so that they can edit it directly.
The issue is I don't know how to set the values returned from the getter to the data function values so that they can be bound with v-model.
HTML
<input type="text" class="form-control" id="nickname1" v-model="name" name="name">
<input type="text" class="form-control" id="address1" placeholder="" v-model="address" name="address" >
<input type="text" class="form-control" id="city1" placeholder="" v-model="city" name="city" >
VUE
data: function() {
return {
name: this.currentArea.title,
address: this.currentArea.address,
city: this.currentArea.city,
state: this.currentArea.state
}
},
computed: {
currentArea() { return this.$store.getters.currentArea }
}
*this.currentArea.title and currentArea.title do not work.
*if I bind the placeholder, the data displays correctly, so the getter function is returning currentArea correctly
The data method is only fired once during initialization, before the computed properties are set up. So, referencing currentArea from within the data method won't work as it will be undefined at the time of execution.
If this.$store.getters.currentArea isn't expected to change in the lifespan of this component, it would be simplest to just set the data properties once in the mounted hook:
data() {
return {
name: '',
address: '',
city: '',
state: ''
}
},
mounted() {
let area = this.$store.getters.currentArea;
this.name = area.name;
this.address = area.address;
this.city = area.city;
this.state = area.state;
}
Or, if you know that the data properties for this component will always be the same as the currentArea, you could simply return this.$store.getters.currentArea in the data method directly:
data() {
return this.$store.getters.currentArea;
}
#thanksd: thank you for your answer.
I am working on a scenario where the state is stored in vuex, temporarily sent incomplete to the component and then updated through a fetch.
And it should be editable in a form.
My solution was to export part of the state with a getter in vuex:
getters: {
getItemDetail: (state, getters) => (id) => {
let item = state.openedItems.items.find(i => i.id === id);
return item ? item.data : null;
}
}
using it in the component by combining data, computed and watch properties (and deep cloning the object with the help of lodash):
data () {
return {
itemDetail: null
};
},
computed: {
itemData () {
return this.$store.getters.getItemDetail(this.item.id);
}
},
watch: {
itemData (n, o) {
this.itemDetail = _.cloneDeep(n);
}
}
Finally I bind the input to "itemDetail" (using an elemen switch, in my example):
<el-switch v-model="itemDetail.property"></el-switch>
To me (but I am quite new to Vue), it seems a good and working compromise.
I am having a problem getting my Insert Autoform to work properply. I am trying to have it similar to the example http://autoform.meteor.com/insertaf and my code is below. I have already removed insecure and autopublish
client/templates/venues/venue_submit.html
<template name="venueSubmit">
<!-- {{> quickForm collection="Venues" id="venueSubmit" type="insert"}} -->
{{#if isSuccessfulvenueSubmit }}
<h2>Thanks for the Venue </h2>
{{else}}
{{#autoForm id="insertVenueForm" type="insert" collection=Collections.Venues omitFields="createdAt" resetOnSuccess=true}}
{{> afQuickField name="Venue"}}
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Venue</button>
<button type="reset" class="btn btn-default">Reset Form</button>
</div>
{{/autoForm}}
{{/if}}
</template>
client/templates/venues/venue_submit.js
Schemas = {};
Template.registerHelper("Schemas", Schemas);
Schemas.Venue = new SimpleSchema({
Venue: {
type: String,
label: "Venue Name",
max: 200,
autoform: {
placeholder: "Name of the Venue"
}
},
....
});
AutoForm.debug()
var Collections = {};
Template.registerHelper("Collections", Collections);
Venues = Collections.Venues = new Mongo.Collection("Venues");
Venues.attachSchema(Schemas.Venue);
Venues.allow({
insert: function (userId, doc) {
return true;
},
remove: function (userID, doc, fields, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
if (Meteor.isClient) {
Meteor.subscribe("Venues")
};
server/Publications.js
Meteor.publish('venue', function () {
return Venues.find(id);
});
The AutoForm insert type generates a document and inserts in on the client. Without the autopublish and insecure packages installed you need to make sure to subscribe to the appropriate collection on the client. It does not exist if you do not subscribe to it.
if (Meteor.isClient) {
Meteor.subscribe("Venues")
}
Your problem is that you have venue_submit.js inside the client folder, but its contents are not intended solely for the client.
You can leave venue_submit.html exactly as it is.
Change venue_submit.js to:
Template.registerHelper("Schemas", Schemas);
AutoForm.debug();
Template.registerHelper("Collections", Collections);
Meteor.subscribe("Venues");
You only need the lines here that relate to the client: the two template helpers, the AutoForm debug (which you don't need except for debugging), and the subscribe to the Venues collection.
Change server/Publications.js to include everything related to the server side:
Meteor.publish('Venues', function () {
return Venues.find({});
});
Venues.allow({
insert: function (userId, doc) {
return true;
},
remove: function (userID, doc, fields, modifier) {
return true;
},
remove: function (userId, doc) {
return true;
}
});
It includes the publish function and the permissions on the collection.
Now create lib/schema.js:
Schemas = {};
Schemas.Venue = new SimpleSchema({
Venue: {
type: String,
label: "Venue Name",
max: 200,
autoform: {
placeholder: "Name of the Venue"
}
}
});
Collections = {};
Venues = Collections.Venues = new Mongo.Collection("Venues");
Venues.attachSchema(Schemas.Venue);
Everything in lib will be available to both the client and server and the contents of this folder will be loaded first so the schema and collection definitions will be available to all the rest of the code. Note the lack of a var keyword for the Collections. Using var sets the scope to only within the file. Omitting it makes the Collections variable available throughout your code.
I am making simple application where user can add some data in the website. Every time, when user adds new 'name' I want display the latest name automatically for every connected users.
I am not sure if my implementation of Template.names.name is a good idea, maybe I should use subscribe instead?
Here is my code:
<template name="names">
<p>What is your name ?</p>
<input type="text" id="newName"/>
<input type="button" id="nameSubmit" value="add new"/>
<p>Your name: {{name}}</p>
</template>
if (Meteor.isClient) {
Template.names.name({
'click input#nameSubmit': function () {
Meteor.call('newName', document.getElementById("newName").value);
}
});
Template.names.name = function () {
var obj = Names.find({}, {sort: {"date": -1}}).fetch()[0];
return obj.name;
};
}
if (Meteor.isServer) {
newName: function (doc) {
var id = Names.insert({
'name': doc,
'date': new Date()
});
return id;
}
}
I use meteorjs version 0.8.1.1.
The only thing I see inherently wrong with your code is your method.. To define methods you can use with Meteor.call you have you create them with a call to Meteor.methods
Meteor.methods({
newName: function (name) {
Names.insert({
'name': doc,
'date': new Date()
});
}
});
Another couple notes.. The Method should be defined in shared space, not just on the server unless there is some specific reason. That why it will be simulated on the client and produce proper latency compensation.
Also in your Template.names.name you can return the result of a findOne instead of using a fetch() on the cursor.
Template.names.name = function () {
return Names.findOne({}, {sort: {"date": -1}}).name;
};
I'm having trouble getting Meteor.publish to update in response to a changing form field. The first call to publish seems to stick, so the query operates in that subset until the page is reloaded.
I followed the approach in this post, but am having no luck whatsoever.
Any help greatly appreciated.
In lib:
SearchResults = new Meteor.Collection("Animals");
function getSearchResults(query) {
re = new RegExp(query, "i");
return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
}
In client:
Session.set('query', null);
Template.searchQuery.events({
'keyup .query' : function (event, template) {
query = template.find('.query').value
Session.set("query", query);
}
});
Meteor.autosubscribe(function() {
if (Session.get("query")) {
Meteor.subscribe("search_results", Session.get("query"));
}
});
Template.searchResults.results = function () {
return getSearchResults(Session.get("query"));
}
On server:
Meteor.publish("search_results", getSearchResults);
Template:
Search for Animals
<body>
{{> searchQuery}}
{{> searchResults}}
</body>
<template name="searchQuery">
<form>
<label>Search</label>
<input type="text" class="query" />
</form>
</template>
<template name="searchResults">
{{#each results}}
<div>
{{_id}}
</div>
{{/each}}
</template>
Update [WRONG]
Apparently, the issue is that the collection I was working with was (correctly) generated outside of Meteor, but Meteor doesn't properly support Mongo's ObjectIds. Context here and related Stackoverflow question.
Conversion code shown there, courtesy antoviaque:
db.nodes.find({}).forEach(function(el){
db.nodes.remove({_id:el._id});
el._id = el._id.toString();
db.nodes.insert(el);
});
Update [RIGHT]
So as it turns out, it was an issue with RegExp / $regex. This thread explains. Instead of:
function getSearchResults(query) {
re = new RegExp(query, "i");
return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
}
At the moment, one needs to do this instead:
function getSearchResults(query) {
// Assumes query is regex without delimiters e.g., 'rot'
// will match 2nd & 4th rows in Tim's sample data below
return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: query, $options: 'i'}} ] }, {limit: 10});
}
That was fun.
PS -- The ddp-pre1 branch has some ObjectId functionality (SearchResults = new Meteor.Collection("Animals", {idGeneration: "MONGO"});)
Here's my working example:
UPDATE the original javascript given was correct. The problem, as noted in the comments, turned out to be that meteor doesn't yet support ObjectIds.
HTML:
<body>
{{> searchQuery }}
{{> searchResults}}
</body>
<template name="searchQuery">
<form>
<label>Search</label>
<input type="text" class="query" />
</form>
</template>
<template name="searchResults">
{{#each results}}
<div>
{{id_species}} | {{name}} - {{_id}}
</div>
{{/each}}
</template>
Javascript:
Animals = new Meteor.Collection("Animals");
function _get(query) {
re = new RegExp(query, "i");
console.log("rerunning query: " + query);
return Animals.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
};
if (Meteor.isClient) {
Session.set("query", "");
Meteor.autosubscribe(function() {
Meteor.subscribe("animals", Session.get("query"));
});
Template.searchQuery.events({
'keyup .query' : function (event, template) {
query = template.find('.query').value
Session.set("query", query);
}
});
Template.searchResults.results = function () {
return _get(Session.get("query"));
}
}
if (Meteor.isServer) {
Meteor.startup(function() {
if (Animals.find().count() === 0) {
Animals.insert({name: "panda", is_active: true, id_species: 'bear'});
Animals.insert({name: "panda1", is_active: true, id_species: 'bearOther'});
Animals.insert({name: "panda2", is_active: true, id_species: 'bear'});
Animals.insert({name: "panda3", is_active: true, id_species: 'bearOther'});
}
});
Meteor.publish("animals", _get);
}