2017-09-04 62 views
0

插入數據我想從一個集合嵌入文檔轉換成另一個,這裏計量單位產品蒙戈/流星:從其他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

回答

0

這很簡單,因爲你已經找到了計量單位的文件,你的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