简体   繁体   中英

How do you set the Meteor.userId() for use within autoform/simple-schema?

Say I want to display a list a user's shopping items once they are logged in. I'm using autoform and simple-schema to generate the form elements. When the user logs in for the first time a blank shopping list form is displayed. When submitting the form the shopping list is saved in the db.

What I want to know is how I can save this data for each user.

Normally I would do something like this:

      ShoppingList.insert({
        name: item_name,
        price: 0,
        createdBy: Meteor.userId()
      });

How would I acheive this using autoform and simple-schema? Would it be possible to do something like this:

Schema.ShoppingList = new SimpleSchema({
item: {
    type: String,
    regEx: /^[a-zA-Z-]{2,25}$/
},
price: {
    type: Number,
    regEx: /^[0-9]{2,25}$/
},
createdBy: {
    type: String,
    value: Meteor.userId()
}
});

Thanks again :)

If you are using also Collection2 then use autoValue:

Schema.ShoppingList = new SimpleSchema({
item: {
    type: String,
    regEx: /^[a-zA-Z-]{2,25}$/
},
price: {
    type: Number,
    regEx: /^[0-9]{2,25}$/
},
createdBy: {
    type: String,
    autoValue:function(){ return this.userId }
}
});

Read more : https://github.com/aldeed/meteor-collection2/

This worked for me:

creatorID: {
    type: String,
    regEx: SimpleSchema.RegEx.Id,
    autoform: {
        type: "hidden",
        label: false
    },
    autoValue: function () { return Meteor.userId() },
}

this.userId() didn't work for me, instead this did:

    autoValue: function() {
        return Meteor.user()._id;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM