我想将一个文档从一个集合嵌入到另一个集合中,这里是一个 UoM 到 Products 。
Template.NewProduct.helpers({
...
uoms: function() {
return UoM.find();
},
...
});
Template.NewProduct.events({
//Submit and Add to Database
'submit form': function(event, template) {
event.preventDefault();
selectedUoM = UoM.findOne({
_id: event.target.uomid.value
});
var doc = {
name: event.target.name.value,
category: event.target.category.value,
suppliers: selectedSup,
uomid: event.target.uomid.value,
};
Products.insert(doc, function(error, result) {
...
});
},
});
========= Collections ===========
import SimpleSchema from 'simpl-schema';
Products = new Mongo.Collection("products");
Products.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Product Name",
max: 200
},
suppliers: {
type: Array,
label: "Suppliers",
},
'suppliers.$' : {type: String},
category: {
type: String,
label: "Category"
},
// Unit: unit , 50kg bag, 25kg bag, 22.5kg barrel etc...
uomid: { //This one is working with UoM._id
type: String,
label: "Unit of Measurement",
},
uom_data: { //Need to populate this one with _id, name, unit, unitname from UoM collection
type: Array,
optional: true
},
<template name="NewProduct">
...
<label for="uomid">Unit of Measurement</label>
<select class="sel2js" name="uomid">
{{#each uoms}}
{{> uomprod}}
{{/each}}
</select>
<button type="submit" class="btn" id="submitNewProduct" value="Submit">Submit</button>
<template name="uomprod">
<option value="{{_id}}">{{name}} - {{unit}} {{unitname}}</option>
</template>
<script type="text/javascript">
$(document).ready(function() {
$(".sel2js").select2();
};
</script>
答案 0 :(得分:0)
非常简单,因为您已经找到了UoM文档,您的selectedUoM
变量将包含一个简单的js对象,该对象可以直接分配给其他集合中的密钥。
selectedUoM = UoM.findOne(event.target.uomid.value);
var doc = {
name: event.target.name.value,
category: event.target.category.value,
suppliers: selectedSup,
uomid: event.target.uomid.value,
uomdata: selectedUoM
};
Products.insert(doc,...
请注意,自uomid === selectedUoM._id
起,您的模型中的冗余很少。您可以轻松地完全删除uomid
密钥。
您还需要更改产品架构,以支持uomdata
的对象,而不是数组! - 您只是插入单个文档,而不是数组。为避免必须指定子结构,您还必须使用blackbox: true
。
uom_data: { //Need to populate this one with _id, name, unit, unitname from UoM collection
type: Object,
optional: true,
blackbox: true
},