蒙戈/流星:从其他MongoDB的收藏

问题描述:

插入数据我想从一个集合嵌入文档转换成另一个,这里计量单位产品蒙戈/流星:从其他MongoDB的收藏

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

欢迎来到Stack Overflow。你需要什么样的帮助?这段代码是否工作?你会得到什么错误信息,以及代码中的哪个地方。 (如果您可以发布此信息以及您的代码,这很有帮助)。请修改您的帖子以添加此 – Mikkel

这很简单,因为你已经找到了计量单位的文件,你的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 
    }, 
+0

非常感谢。我花了整整一天的时间试图获得答案。 – CHiEZ