官术网_书友最值得收藏!

On the server

On the server-side, we have two files: index.js and insertData.js. There is also a private folder where we can define sample data that we can work with. Meteor will treat the private folder as an assets folder and will not bundle it with the rest of the execution code, which makes it a perfect place to have the test data.

In the private folder in file, products.json will have the following fields:

private/products.json

The fields of the Products collection are as follows:

id: This is the product ID.

title: This refers to a product title.

price: This is the price per unit.

inventory: This is the currently available product inventory in the store.

department: This refers to the department ID the product belongs to.

In the root of the application tree, we also have a shared folder where we can have modules used by both the client and the server.

In there, we define the two Collections that we will be using: Products and Cart:

export const ProductsCollection = new Mongo.Collection('products');
export const CartCollection = new Mongo.Collection('cart');

The simplest way to insert the data is through a looping in the JSON file and call the collection.insert() query on each iteration:

export default function() {
if (ProductsCollection.find().count() > 0) {
return;
}
const products = JSON.parse(Assets.getText('products.json'));
_.each(products, function(product) {
ProductsCollection.insert(product);
});
}

When we boot the server, this script will run and insert the data from the products.json. We insert data only if the Products collection is empty.

In the server/index.js, the code is as follows:

import insertData from './insertData';
Meteor.startup(() => {
insertData()
...
主站蜘蛛池模板: 宣化县| 葵青区| 将乐县| 梁山县| 平江县| 长沙县| 长垣县| 新郑市| 大庆市| 凤山市| 湟中县| 嵩明县| 长沙市| 青冈县| 肥乡县| 马山县| 达拉特旗| 正宁县| 辰溪县| 石泉县| 阳江市| 郸城县| 成安县| 揭阳市| 星座| 许昌市| 拉萨市| 定远县| 吴忠市| 扎鲁特旗| 六盘水市| 太湖县| 盐亭县| 西和县| 普格县| 泽普县| 达尔| 新昌县| 弋阳县| 罗山县| 吉安县|