1

我有两个系列颜色和汽车。车上可能要选颜色。

如何保存/更新集合中的对象,以便在 Car 对象中嵌入 Color 对象?

 Cars = new Mongo.Collection('cars');
    Cars.attachSchema(new SimpleSchema({
        colorId: {
            label: 'Color',
            type: String,
            autoform: {
                options: function () {
                    return Colors.find().map(function (p) {
                        return {label: p.colorName, value: p._id};
                    });
                },
                label: false
            }
        },

        color: {
            type: Object,
        },
        'color._id': {
            type: String,
            autoform: {
                omit: true,
            },
        },
        'color.colorName': {
            type: String,
            autoform: {
                omit: true,
            },
        },
        'color.colorCode': {
            type: String,
            autoform: {
                omit: true,
            },
        },
    }));


Colors = new Mongo.Collection('colors');
Colors.attachSchema(new SimpleSchema({
    colorName: {
        type: String,
        label: "Color Name",
        max: 20,
    },
    colorCode: {
        type: String,
        optional: true,
        label: "Color Code",
        autoform: {
            afFieldInput: {
                type: "color"
            }
        }
    },
}));

我尝试使用 AutoForm.hooks({ insertCarForm: {before: {

但它没有用

4

1 回答 1

1

有几种方法可以实现这一点,解决方案在很大程度上取决于您可能使用的任何相关包。如果没有看到创建新“卡片”的现有代码,很难给出一个工作示例。不过,这里是一个使用核心 Meteor API 的示例。

  1. 假设你定义了一些表单模板(我称之为'manageCar'),你会做这样的事情。

定义一个 Meteor 方法来处理插入/更新汽车。

Meteor.methods({
  updateCar: function(carDoc) {
    check(carDoc, { /* carDoc schema */ });

    const color = Colors.findOne(carDoc.colorId);
    carDoc.color = color;

    if (carDoc._id) {
      Cars.update(carDoc._id, {
        $set: {
          colorId: carDoc.colorId,
          color: carDoc.color,      
        }
      })
    } else {
      Cars.insert(carDoc);
    }
  },
});

为调用定义的方法的表单提交添加一个事件处理程序。

Template.manageCar.events({
  'click .js-save-car'(event, instance) {
    const data = {
      _id: event.target._id.value,
      colorId: event.target.colorId.value
    };

    Meteor.call('updateCar', data, function(error, result) {
      if (!error) {
        alert('Car updated successfully');
      }
    });
  }  
});

长话短说,您只需要确保您可以访问您为 Car 保存的 Color id,然后确保您在 Color 集合上执行查找以检索必要的 Color 文档,然后将其用于您的 Car 插入或更新。

如果您有任何问题或需要进一步解释,请告诉我。

于 2017-02-23T16:52:05.700 回答