显示 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 文档