顯示 MongoDB 集合

此示例顯示如何在 React 元件中顯示 MongoDB 集合。該集合在伺服器和客戶端之間不斷同步,並且隨著資料庫內容的改變,頁面立即更新。

要連線 React 元件和 Meteor 集合,你需要 react-meteor-data 包。

$ meteor add react-meteor-data
$ meteor npm install react-addons-pure-render-mixin

both/collections.js 中宣告瞭一個簡單的集合。both 目錄中的每個原始檔都是客戶端和伺服器端程式碼:

import { Mongo } from 'meteor/mongo';

// This collection will contain a list of random numbers
export const Numbers = new Mongo.Collection("numbers");

該集合需要在伺服器上釋出。在 server/publications.js 中建立一個簡單的出版物:

import { Meteor } from 'meteor/meteor';
import { Numbers } from '/both/collections.js';

// This publication synchronizes the entire 'numbers' collection with every subscriber
Meteor.publish("numbers/all", function() {
  return Numbers.find();
});

使用 createComponent 函式,我們可以將反應值(如 Numbers 集合)傳遞給 React 元件。client/shownumbers.jsx

import React from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Numbers } from '/both/collections.js';

// This stateless React component renders its 'numbers' props as a list
function _ShowNumbers({numbers}) {
  return <div>List of numbers:
    <ul>
      // note, that every react element created in this mapping requires 
      // a unique key - we're using the _id auto-generated by mongodb here
      {numbers.map(x => <li key={x._id}>{x.number}</li>)}
    </ul>
  </div>;
}

// Creates the 'ShowNumbers' React component. Subscribes to 'numbers/all' publication,
// and passes the contents of 'Numbers' as a React property.
export const ShowNumbers = createContainer(() => {
  Meteor.subscribe('numbers/all');
  return {
    numbers: Numbers.find().fetch(),
  };
}, _ShowNumbers);

最初,資料庫可能是空的。

StackOverflow 文件

將條目新增到 MongoDB 並觀察頁面自動更新。

$ meteor mongo 
MongoDB shell version: 3.2.6
connecting to: 127.0.0.1:3001/meteor

meteor:PRIMARY> db.numbers.insert({number: 5});
WriteResult({ "nInserted" : 1 })

meteor:PRIMARY> db.numbers.insert({number: 42});
WriteResult({ "nInserted" : 1 })

StackOverflow 文件