簡體   English   中英

Mongo / Meteor:插入其他MongoDB集合中的數據

[英]Mongo/Meteor: Insert data from from other MongoDB Collection

我想將一個集合中的文檔嵌入到另一個集合中,這里將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> 

這很簡單,因為您已經找到了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
  },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM