I'm trying to create a field modifiedBy with type: Object (to Meteor users).
I see you can setup blackbox: true for a Custom Object, but if I want to setup to a specific Object say a Group (collection) field modifiedBy is the logged in user, any pointers/help is greatly appreciated.
Thanks
As far as I see it, you have two options:
Store user-ids there with type: String
Denormalize it as you proposed
Denormalize it as you proposed
To denormalize it you can do something like this inside your schema:
...
modifiedBy: {
type: object
}
'modifiedBy._id': {
type: String,
autoValue: function () {
return Meteor.userId()
}
}
'modifiedBy.username': {
type: String,
autoValue: function () {
return Meteor.user().username
}
}
...
As you pointed out, you'd want to update these properties when they change:
server-side
Meteor.users.find().observe({
changed: function (newDoc) {
var updateThese = SomeCollection.find({'modifiedBy.username': {$eq: newDoc._id}})
updateThese.forEach () {
SomeCollection.update(updateThis._id, {$set: {name: newDoc.profile.name}})
}
}
})
Store user-ids there with type: String
I'd recommend storing user-ids. It's cleaner but it doesn't perform as well as the other solution. Here's how you could do that:
...
modifiedBy: {
type: String
}
...
You could also easily write a Custom Validator for this. Now retrieving the Users is a bit more complicated. You could use a transform function to get the user objects.
SomeCollection = new Mongo.Collection('SomeCollection', {
transform: function (doc) {
doc.modifiedBy = Meteor.users.findOne(doc.modifiedBy)
return doc
}
})
But there's a catch: "Transforms are not applied for the callbacks of observeChanges or to cursors returned from publish functions."
This means that to retrieve the doc reactively you'll have to write an abstraction:
getSome = (function getSomeClosure (query) {
var allDep = new Tacker.Dependency
var allChanged = allDep.changed.bind(allDep)
SomeCollection.find(query).observe({
added: allChanged,
changed: allChanged,
removed: allChanged
})
return function getSome () {
allDep.depend()
return SomeCollection.find(query).fetch()
}
})
Related
Forms of this question have been asked a few times, but I've been unable to find a solution:
I have a schema like this (simplified):
StatusObject = new SimpleSchema({
statusArray: [statusSchema]
});
where statusSchema is
{
topicId:{
type: String,
optional: true
},
someInfo:{
type: Number,
optional: true,
decimal: true
},
otherInfo:{
type: Number,
optional: true
}
}
I am trying to upsert - with the following meteor method code:
var upsertResult = BasicInfo.update({
userId: this.userId,
statusArray: {
$elemMatch: { topicId : newStatus.topicId }
}
}, {
$set: {
"statusArray.$.topicId": newStatus.topicId,
"statusArray.$.someInfo": newStatus.someInfo,
"statusArray.$.otherInfo": newStatus.otherInfo
}
}, {
multi: true,
upsert: true
});
But I keep getting an error: statusArray must be an array
I thought by adding the $, I was making sure it is recognized as an array? What am I missing?
It seems (after your clarification comments), that you want to find a document with particular userId and modify its statusArray array using one of these scenarios:
Update existing object with particular topicId value;
Add a new object if the array doens't have one with particular topicId value.
Unfortunately, you can't make it work using just one DB query, so it should be like this:
// try to update record
const updateResult = BasicInfo.update({
userId: this.userId,
'statusArray.topicId': newStatus.topicId
}, {
$set: {
"statusArray.$": newStatus
}
});
if (!updateResult) {
// insert new record to array or create new document
BasicInfo.update({
userId: this.userId
}, {
$push: {
statusArray: newStatus
},
$setOnInsert: {
// other needed fields
}
}, {
upsert: true
});
}
Your code is treating StatusArray as an object,
Before you do the upsert, build the status array first, assuming that your current value is currentRecord
newStatusArray = currentRecord.statusArray
newStatusArray.push({
topicId: newStatus.topicId,
someInfo : newStatus.someInfo,
otherInfo: newStatus.otherInfo
})
and in the upsert, simply refer to it like this
$set: { statusArray: newStatusArray}
I'm trying to insert an array into an object and I'm not having any luck. I think the schema is rejecting it based on validation but I'm not sure why. If I console.log(this.state.typeOfWork) and check typeof it states its an Object which contains:
(2) ["Audit - internal", "Audit - external"]
0: "Audit - internal"
1: "Audit - external"
My collection after an update contains:
"roleAndSkills": {
"typeOfWork": []
}
Example: Schema
roleAndSkills: { type: Object, optional: true },
'roleAndSkills.typeOfWork': { type: Array, optional: true },
'roleAndSkills.typeOfWork.$': { type: String, optional: true }
Example: update
ProfileCandidate.update(this.state.profileCandidateCollectionId, {
$set: {
roleAndSkills: {
typeOfWork: [this.state.typeOfWork]
}
}
});
Simple schema has some problems with validation on Objects or Arrays, i had the same problem in a recent app i developed.
What can you do?
well, what i did, on the Collections.js file, when you are saying:
typeOfWork:{
type: Array
}
Try adding the property blackbox:true, like this:
typeOfWork:{
blackbox: true,
type: Array
}
This will tell your Schema that this field is taking an Array, but ignore further validation.
The validation i made was on main.js, just to be sure i had no empty array and the data was plain text.
As requested here is my update method, im my case i used objects not arrays but it works the same way.
editUser: function (editedUserVars, uid) {
console.log(uid);
return Utilizadores.update(
{_id: uid},
{$set:{
username: editedUserVars.username,
usernim: editedUserVars.usernim,
userrank: {short: editedUserVars.userrank.short,
long: editedUserVars.userrank.long},
userspec: {short: editedUserVars.userspec.short,
long: editedUserVars.userspec.long},
usertype: editedUserVars.usertype}},
{upsert: true})
},
here it the collection schema
UtilizadoresSchema = new SimpleSchema({
username:{
type: String
},
usernim:{
type: String
},
userrank:{
blackbox: true,
type: Object
},
userspec:{
blackbox: true,
type: Object
},
usertype:{
type: String
}
});
Utilizadores.attachSchema(UtilizadoresSchema);
Hope it helps
Rob
typeOfWork is an Array. You should push your value in it :
$push: {
"roleAndSkills.typeOfWork": this.state.typeOfWork
}
for multiple values :
$push: {
"roleAndSkills.typeOfWork": { $each: [ "val1", "val2" ] }
}
mongo $push operator
mongo dot notation
You state that this.state.typeOfWork is an array (of strings) but then when you .update() your document you are enclosing it in square brackets:
ProfileCandidate.update(this.state.profileCandidateCollectionId, {
$set: {
roleAndSkills: {
typeOfWork: [this.state.typeOfWork]
}
}
});
Simply remove the redundant square brackets:
ProfileCandidate.update(this.state.profileCandidateCollectionId, {
$set: {
roleAndSkills: {
typeOfWork: this.state.typeOfWork
}
}
});
Also since your array is just an array of strings you can simplify your schema a bit by declaring it as such with [String] for the type:
'roleAndSkills.typeOfWork': { type: [String] }
Note furthermore that objects and arrays are by default optional so you can even omit the optional flag.
I have an app in Meteor and the idea is that an admin user can add a document and assign it to one of its customers (customers are stored in the user collection). So I would like to present a dropdownbox with customers on the document insert view. The relevant code of the schema is below:
customer: {
type: [String],
label: "Customers",
allowedValues: function () {
return Meteor.users.find().map(function (user) {
return user._id
});
},
autoform: {
options: function () {
return Meteor.users.find({}).map(function(user) {
return {
value: user._id,
label: user.profile.name
}
})
}
},
optional: true
}
When I put a type: String (instead of [String]) it shows the current user only in a dropdownbox. If I use [String] (as it should be), the dropdownbox actually turns in a text box (it does not have the typical dropdown behaviour) with 3 fields (for all the users it found), yet it only shows the first one again but leaves placeholders for the other 2.
The view uses:
{{> afQuickField name='customer'}}
IMPORTANT: The account package, by default doest not publish the users collection. You will have to write a new publication method in your server and corresponding subscription in your client for this to work.
No read on..
Well.. This is a bit tricky. Look at the code below and edit your 'autoform' section accordingly.
autoform: {
options: function () {
var options = [];
Meteor.users.find().forEach(function (element) {
options.push({
label: element.profile.name, value: element._id
})
});
return options;
}
}
the required syntax for selection box 'options' is:
options:{[label,value],...}
The above code reads all the rows from the user collection, and pushes each row to an array called 'options' as an array.
Hope this helps or gives you some insights.
Please note that the above only works if your collection subscription/publication are proper.
Look at the following code to get a simple idea.
if (Meteor.isClient) {
Meteor.subscribe('allUsers')
}
if (Meteor.isServer) {
Meteor.publish('allUsers', function() {
return Meteor.users.find({}, {fields:{username:1,emails:1}})
})
}
I've got a form created through AutoForm.
As far as data sources, I can fill in parts of the form and use:
AutoForm.getFormValues('form-id').insertDoc // returns the contents of the form
When I validate the form I can do:
var formValues = AutoForm.getFormValues('form-id').insertDoc;
var isValid = MyCollection.simpleSchema().namedContext("myContext").validate(formValues);
// if isValid returns true, then I enable the Submit button
Instead of filling in parts of the form, I want to manually add information into whatever object Autoform uses for validation and submission to a collection.
For example, there are data fields in the schema that simply don't need to appear in the form itself.
Take a shopping cart:
ShoppingCartSchema = {
totalPrice: {
type: Number,
optional: false
},
itemsSelected: {
type: [Object],
optional: false
}
};
The data for itemsSelected is obviously provided through user input on the form.
The data for totalPrice is something that should not be from a form input. It's generated in the code.
But totalPrice still needs to be validated as a required field before AutoForm submits the form to a collection.
So how do you add totalPrice onto the object that Autoform eventually validates?
You could use an autovalue if you wanted to.
ShoppingCartSchema = new SimpleSchema({
'items': {
type: [Object],
},
'items.$.name': {
type: String
},
'items.$.price': {
type: Number
},
totalPrice: {
type: Number,
autoValue: function () {
if (this.field('items').isSet) {
let total = this.field('items').value.reduce(function (sum, item) {
return sum + item.price;
}, 0);
if (this.isInsert) {
return total;
} else {
return { $set: total };
}
}
}
},
});
Autoform Hooks can help you manipulate the data before you save it into the Collection.
In your case .
AutoForm.hooks({
form-id: { // The Autoform ID
onSubmit: function (insertDoc, updateDoc, currentDoc) {
if (customHandler(insertDoc)) { // Your Logic here
this.done(); // This is Required
} else {
this.done(new Error("Submission failed"));
}
return false;
}
}
});
For More Information Please refer Autoform Readme
I'm retrieving a Collection document based on a Session variable, and then passing this as a variable called store through an iron:router data context. The problem is that it sometimes returns undefined, as if it had not prepared itself in time for the helper to execute. How do I ensure the variable is always defined before the helper/template runs?
Here's my route, you can see that the data context includes retrieving a doc from a collection based on an _id stored in a Session variable:
Router.route('/sales/pos', {
name: 'sales.pos',
template: 'pos',
layoutTemplate:'defaultLayout',
loadingTemplate: 'loading',
waitOn: function() {
return [
Meteor.subscribe('products'),
Meteor.subscribe('stores'),
Meteor.subscribe('locations'),
Meteor.subscribe('inventory')
];
},
data: function() {
data = {
currentTemplate: 'pos',
store: Stores.findOne(Session.get('current-store-id'))
}
return data;
}
});
And here is the helper which relies on the store variable being passed to the template:
Template.posProducts.helpers({
'products': function() {
var self = this;
var storeLocationId = self.data.store.locationId;
... removed for brevity ...
return products;
}
});
This is a common problem in Meteor. While you wait on your subscriptions to be ready, this does not mean your find function had time to return something. You can solve it with some defensive coding:
Template.posProducts.helpers({
'products': function() {
var self = this;
var storeLocationId = self.data.store && self.data.store.locationId;
if (storeLocationId) {
... removed for brevity ...
return products;
}
}
});