Mongo中的集合之间的关系

时间:2016-05-18 06:01:26

标签: mongodb meteor

现在我正在开发一个电子商务应用程序,我使用Meteor 1.3。 现在我一直坚持定义两个集合之间的关系。我有两个,让我们说ProductsCustomers,我使用meteor-collection-helpers来管理这项任务,现在我的代码看起来像这样:

Products.js

import {Mongo} from 'meteor/mongo';
import {Customers} from './customers.js';

export const Products = new Mongo.Collection('products');

Products.helpers({
    getName() {
        return this.productName;
    },
    getId() {
        return this._id;
    },
    customers() {
        return Customers.findOne(this.customerId);
    }
});

Customers.js

import {Mongo} from 'meteor/mongo';
import {Products} from './products.js';

export const Customers = new Mongo.Collection('customers');

Customers.helpers({
    tours() {
        return Products.find({customerId: this._id});
    }
});

这是将新客户插入Customers集合的方法:

 Customers.insert({
      name,
      phone,
      email,
      productId: Products.findOne().getId(),
      product: Products.findOne().getName(),
      createdAt: new Date(),
 });

订单提交后我得到一个新文件,但问题是我可以正确应用第一个文件的插入方法,当我尝试提交第二个订单的订单时此文件仍然抓取第一个的名称和ID文档,所以现在使用这个表单是没有意义的。 我实际上在google搜索时改变了很多代码,但结果却没有任何东西,并且保存了我向你展示的部分,因为至少它只适用于唯一的第一个产品。 我想我在定义productId方法时做错了但却无法得到它,所以我希望在这里找到帮助。任何建议都会受到热烈欢迎,如果我在本主题的任何帖子之前发现我的错误,我会定义它。

UPD

解决方案尽可能简单,我也不需要上面写的包。 正确的查询是product: Products.findOne(this.props.product._id).productName,这就是诀窍。

1 个答案:

答案 0 :(得分:1)

基本上你自己发现问题但不知道解决方案。除非您传递Products.findOne()这样的论点,否则Products.findOne({_id :'id'})将始终返回第一个文档。