我想寫一個表中有不同數量的行和列到數據庫。爲此,我有一個保存表格標題的Criterion
集合以及一個保存表格數據的集合Option
。流星方法插入不工作(mongodb)
的結構是這樣的:
Criterion
爲:{ { "_id" : "hId1", "name" : "Option Name", "tableId" : "tId1" }, { "_id" : "hId2", "name" : "Rent", "score" : 9, "tableId" : "tId1" }, { "_id" : "hId3", "name" : "Surface", "score" : 5, "tableId" : "tId1" }, { "_id" : "hId4", "name" : "Price", "score" : 5, "tableId" : "tId1" }, { "_id" : "hId5", "name" : "CPU", "score" : 5, "tableId" : "tId4" } etc. }
爲
Option
:{ { "_id" : "id1", "score" : 5, "hId1" : { "value" : "Apt 1" }, "hId2" : { "value" : "800 sqft", "score" : 1 }, "hId3" : { "value" : "$800", "score" : 3 }, etc. "tableId" : "tId1" } { "_id" : "id2", "score" : 5, "hId1" : { "value" : "Apt 2" }, "hId2" : { "value" : "780 sqft", "score" : 10 }, "hId3" : { "value" : "$700", "score" : 3 }, etc. "tableId" : "tId1" } etc. }
Criterion
的第一行將始終有"Option Name"
。對於上述數據,與"tableId" = "tId1"
表將最終看起來像這樣(tableId
和headerId
是關鍵):
| Option Name | Surface | Price |
| =========== | ======== | ===== |
| Apt 1 | 800 sqft | $800 |
| Apt 2 | 780 sqft | $700 |
我的代碼看起來像這樣(imports/api/comparison.js
):
/**
* Options are for the rows
*/
export var Option = new Mongo.Collection('option');
/**
* Criteria are the columns
*/
export var Criterion = new Mongo.Collection('criterion');
Meteor.methods({
'comparison.insertRow' (query, headerId, tableId, isFirst) {
check(query, Object);
check(headerId, String);
check(tableId, String);
check(isFirst, Boolean);
if(isFirst){
var data = {};
data._id = headerId;
data.tableId = tableId;
data.name = "Option Name";
Criterion.insert(data);
}
query._id = tableId;
Option.insert(query);
},
});
哪裏isFirst
是表示這是否是表中第一行的布爾值。
我的查詢構造像這樣(imports/ui/Menu/DataInsert.jsx
):
var query = {};
query.score = // value
// get the header separately
query[headerId] = {
value: //valueH from form
};
// Find the text field via the React ref
for (var i = 1, len = cols.length; i < len; i++) {
query[cols[i]._id] = {
value: //valueV from form,
score: //valueS from form
};
}
我的文件可在服務器上,因爲我做這server/main.js
:import '../imports/api/comparison.js';
的query
被插入沒問題到Option
沒有問題。
爲什麼不是data
插入Criterion
(當isFirst = true
)?
我做了console.log(data)
和console.log(query)
,它看起來像這樣:
這可能是因爲您在插入之前手動設置了_id字段。您應該添加一個回調作爲第二個參數給Criterion.insert,它接受一個錯誤對象作爲第一個參數。用它來檢查插入是否拋出錯誤。閱讀[api]的服務器**部分的**(http://docs.meteor.com/api/collections.html#Mongo-Collection-insert) – jordanwillis