Meteor collections: upsert w/ array - meteor

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}

Related

Validation error with simple-schema

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.

Difference between defaultValue and autoValue in Autoform?

I'm working on a project which I start with using autoValue as
Programs.attachSchema(new SimpleSchema({
createdBy: {
type: String,
autoValue: function() {
return this.userId
},
optional: true,
autoform: {
type: 'hidden'
}
},
createdAt: {
type: Date,
label: "Created At",
defaultValue: new Date(),
optional: true,
autoform: {
type: 'hidden'
}
}
}));
everything works find until I need to update the information by other users, let's say admin, Programs.update or Programs.insert methods will change the email field.
I tried to use defaultValue for createdBy field but
defaultValue: this.userId
return me null
and i'm not allowed to use
defaultValue: Meteor.userId()
Can anyone explain the difference? I tried use function() {return this.userId} for defaultValue which still got no luck
defaultValue is used by simple-schema for defining default value. There are some quirks so read the docs: https://github.com/aldeed/meteor-simple-schema#defaultvalue
Think of when the code is ran and you will understand why you can't use Meteor.userId() or this.userId for defaultValue. The schema is ran once at startup.
What allows autoValue to work is that it returns a function. The function is ran during db updates/inserts. Read over the docs to fully understand it: https://github.com/aldeed/meteor-simple-schema#autovalue
Now, if I understand your question properly, you have issues with autoValue when an admin comes along and modifies the document? Causing the createdBy to be set to the admin's id? To solve something like that, you just need to be more specific with your autoValue function.
See if this code helps guide you in the proper direction:
Programs.attachSchema(new SimpleSchema({
createdBy: {
type: String,
autoValue: function() {
if (this.isInsert) {
return this.userId;
} else if (this.isUpsert) {
return { $setOnInsert: this.userId };
}
this.unset(); // Prevent user from supplying their own value
return undefined;
},
optional: true,
autoform: {
type: 'hidden'
}
},
createdAt: {
type: Date,
label: 'Created At',
defaultValue: new Date(),
optional: true,
autoform: {
type: 'hidden'
},
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return { $setOnInsert: new Date() };
}
this.unset(); // Prevent user from supplying their own value
return undefined;
},
}
}));
You should try this snippet,
new SimpleSchema({
// ...
createdBy: {
autoValue() {
return Meteor.userdId();
}
}
// ...
})
Now the explanation, Your problem is more likely related with the this binding, this.userId, was called from SimpleSchema context in this way this does not have any userId() method, you should use the full namespace in this case Meteor.userId();
A very cool explanation on this binding I recommend you to read
This binding

how to set a default value to element in a collection of type [String]?

i have quickform once the submit button clicked, this method is fired
submitPost: function (app) {
check(app, {
title: String,
description: String,
category: String,
price: Number
});
var knownId = Products.insert(app);
Products.update({ _id: knownId }, { $set:{screenShots: scs, previewImage: pi, sourceCode: zip }});
}
the submit button wasn't working when i didn't give "screenShots, previewImage, and sourceCode" a default values in a collection.
Once i gave them a default value like it is shown below
previewImage: {
type: String,
defaultValue: "jjj",
},
sourceCode: {
type: String,
defaultValue: "jjj",
},
screenShots: {
type: [String],
autoValue: function() {
return [];
}
},
now the submit button in the form is working and the update method is triggered. it updates both "previewImage and sourcCode" but "screenShots" is still empty.
am not sure but i believe the problem has to do with autoValue which i should make it a default value, but how do i give an element that of type array of string a default value?
or the problem has to do with something else?
use optional: true in the schema if the value is optional, and it will pass check if it is empty.
The autoValue option is provided by the SimpleSchema package and is documented there. Collection2 adds the following properties to this for any autoValue function that is called as part of a C2 database operation:
isInsert: True if it's an insert operation
isUpdate: True if it's an update operation
isUpsert: True if it's an upsert operation (either upsert() or upsert: true)
So If you want to provide the autoValue while updating you have to use isUpdate in your schema like this.
createdAt: {
type: Date,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset(); // Prevent user from supplying their own value
}
}
},
So your schema will be something like this:
previewImage: {
type: String,
defaultValue: function() {
if (this.isInsert) {
return 'fff';
} else if (this.isUpdate) {
return 'fff';
}
},
sourceCode: {
type: String,
defaultValue:function() {
if (this.isInsert) {
return 'jjj';
} else if (this.isUpdate) {
return 'jjj';
}
},
screenShots: {
type: [String],
autoValue: function() {
if (this.isInsert) {
return [];
} else if (this.isUpdate) {
return [];
}
}
},
For more info please check this

meteor - How to add a subdocument as reference with SimpleSchema

I have the following SimpleSchema
Schema.Team = new SimpleSchema({
name:{
type:String
},
members: {
type: [Schema.User],
optional:true
}
});
I would like to insert (on the server) a new team document with the current user, as a reference (not as an embedded document).
I have tried:
Teams.insert({name:"theName",members:[Meteor.user()]}) // works but insert the user as an embedded doc.
Teams.insert({name:"theName",members:[Meteor.user()._id]}) // Error: 0 must be an object
I have also tried in two steps:
var id = Teams.insert({name:teamName});
Teams.update({ _id: id },{ $push: { 'users': Meteor.user()._id } });
Then I have another error I don't understand: Error: When the modifier option is true, validation object must have at least one operator
So how can I insert a document with a reference to another schema?
If you just want to store an array of userIds in your Team collection try:
Schema.Team = new SimpleSchema({
name:{
type:String
},
members: {
type: [String],
optional:true
}
});
Then
Teams.insert({ name: "theName", members: [Meteor.userId()] });
Should work. Later when you want to add an additional id you can just:
Teams.update({ _id: teamId },{ $addToSet: { members: Meteor.userId() }});
The following is probably the syntax you are after, assuming you are also using AutoForm.
If you are using collection2, you can also add an autovalue for when a team is created to automatically add the creator to that team for more convenience.
Schema.Team = new SimpleSchema({
name: {
type:String
},
members: {
type: [String],
defaultValue: [],
allowedValues: function () {
// only allow references to the user collection.
return Meteor.users.find().map(function (doc) {
return doc._id
});
},
autoform: {
// if using autoform, this will display their username as the option instead of their id.
options: function () {
return Meteor.users.find().map(function (doc) {
return {
value: doc._id,
label: doc.username // or something
}
})
}
},
autoValue: function () {
if (this.isInsert && !this.isFromTrustedCode) {
return [this.userId];
}
}
}
});

How to change a schema key?

I have a schema defined below and how can I change the predefined schema key (summary: key) via meteor template?
Schemas.Books = new SimpleSchema(
{
summary: {
type: String
}
}
);
For instance, I want to change this key through a session variable that was defined by router or through a user input.
Not Sure, Try this
If your schema is like this
Books = new SimpleSchema(
{
summary: {
type: String
}
}
);
then in tempalte helpers,
Books._schema.summary.type = function() {
return Session.get("typeValue");
};
In my project I have schema like this
RegisterSchema = new SimpleSchema({
name: {
type: String
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email
},
password: {
type: String,
label: "Password",
min: 8
},
confirmPassword: {
type: String,
label: "Confirm Password",
min: 8,
custom: function () {
if (this.value !== this.field('password').value) {
return "passwordMismatch";
}
}
}
});
and I'm dynamically setting optional value for email like
RegisterSchema._schema.email.optional = function() { return true };
this worked for me.
All d best
This is not the thing that I'm trying to do but I have learned a new trick : )
I want to change the schema key that I described above like this.
Books = new SimpleSchema(
{
bookName: {
type: String
}
}
);
Changing summary: with bookName:
Actually I want to define schema keys dynamically with respect to user information (userId, userName etc.).

Resources