使用Meteor Simpleschema嵌套对象

时间:2017-02-10 21:34:11

标签: meteor meteor-autoform simple-schema

我是Meteor的新手,我正在尝试在我正在构建的应用中使用SimpleSchema / Autoforms。当用户创建组时,他们会填写组名,描述和位置(地址)。在幕后,它们被添加为组的第一个成员,地址将很快转换为lat / lng值。

当我尝试保存时,locationmembers[0]是空对象。

架构:

Groups = new Mongo.Collection('groups');
Groups.attachSchema(new SimpleSchema({
groupName: {
    type: String,
    label: "Group Name",
    max: 200
},
createdBy: {
    type: String,
    autoform: {
        omit: true
    }
},
members: {
    type: [{
        _id: {type: String},
        firstName: {type: String},
        lastName: {type: String}
    }],
    label: "Group Members",
    autoform: {
        omit: true
    }
},
location: {
    type: {
        address: {type: String},
        lat: {type: String},
        lng: {type: String}
    },
    label: "Location"
},
description: {
    type: String,
    label: "Group Description",
    max: 250,
    optional: true
}
}));

插入表格:

Template.groupsList.events({
'submit form': function(e) {
    console.log('submitting form..');
    e.preventDefault();

    var group = {
        groupName: $(e.target).find('[name=groupName]').val(),
        createdBy: Meteor.userId(),
        members: [{
            _id: Meteor.userId(),
            firstName: Meteor.user().profile.firstName,
            lastName: Meteor.user().profile.lastName
        }],
        location: setLocation($(e.target).find('[name=location]').val()),
        description: $(e.target).find('[name=description]').val()
    };

    function setLocation(location) {
        return {
            location: location,
            lat: 123,
            lng: 123
        };
    }
    console.log(group);
    var groupId = Groups.insert(group);
    Router.go('/group/' + groupId);
}
});

我已经看到一些类似的问题发布到Stack Overflow关于此,但数据似乎总是从手头的问题更加模糊。我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:1)

您希望嵌套实际架构而不是普通对象:

Groups = new Mongo.Collection('groups');

const memberTypes = new SimpleSchema({
  _id: {type: String},
  firstName: {type: String},
  lastName: {type: String}
});
const locationType = new SimpleSchema({
  address: {type: String},
  lat: {type: String},
  lng: {type: String}
});

Groups.attachSchema(new SimpleSchema({
  groupName: {
    type: String,
    label: "Group Name",
    max: 200
  },
  createdBy: {
    type: String,
    autoform: {
        omit: true
    }
  },
  members: {
    type: [memberTypes],
    label: "Group Members",
    autoform: {
        omit: true
    }
  },
  location: {
    type: locationType,
    label: "Location"
  },
  description: {
    type: String,
    label: "Group Description",
    max: 250,
    optional: true
  }
}));