【问题标题】:Insert data in collection at Meteor's startup在 Meteor 启动时在集合中插入数据
【发布时间】:2015-09-07 15:55:55
【问题描述】:

我想在 Meteor 启动时插入数据。 (从 JSON 文件之后)

在启动时,我创建了一个新帐户,我想插入数据并将其链接到此帐户。

这是在启动时创建新帐户的代码:

if(!Meteor.users.findOne({emails: { $elemMatch: { address: "test@test.com"}}})){
    var id = Accounts.createUser({ email: "test@test.com", password: "1234", profile: { name: 'Test' } });
    Meteor.users.update({_id: id }, { $set: { admin: false }});
}

然后,我需要插入数据并将其链接到该帐户及其 ID。 (在不同的集合中)。

所以我尝试做类似的事情,但显然它没有工作:

UserData = new Mongo.Collection('user_data');

    if(!Meteor.users.findOne({emails: { $elemMatch: { address: "test@test.com"}}})){
        var id = Accounts.createUser({ email: "test@test.com", password: "1234", profile: { name: 'Test' } });
        Meteor.users.update({_id: id }, { $set: { admin: false }});
        UserData.insert({
            createdBy: id,
            firstname: "test",
            /* ... */
        });
    }

编辑

抱歉没说清楚。

真正的问题是:

UserData = new Mongo.Collection('user_data'); 

声明在另一个文件中,所以我不能像上面那样做。

由于它不在同一个文件中,我尝试获取获得“test@test.com”作为电子邮件的 userId(启动时创建的帐户电子邮件)。一旦我得到它,我想在“createdBy:ID_HERE”中使用它。

【问题讨论】:

  • 你能添加一个描述到底是什么不起作用吗?
  • 是的,抱歉,我刚刚进行了编辑 :)

标签: javascript json meteor startup


【解决方案1】:

好的,您需要查看Structuring your application。您必须更早地加载具有定义的文件,或者稍后加载具有fixture 的文件。

通常,您的集合在 lib/ 中,fixtures 在 server/fixtures.js 中。

因此,如果您将插入代码放入 server/fixtures.js,它将起作用。

【讨论】:

  • 谢谢!我将更改我的应用程序树,但你能告诉我如何让 userId 链接到电子邮件“test@test.com”吗?
  • 这个Meteor.users.findOne({emails: { $elemMatch: { address: "test@test.com"}}}) 返回一个用户document。所以你可以简单地做Meteor.users.findOne({emails: { $elemMatch: { address: "test@test.com"}}})._id(服务器端)
  • 现在可以使用了,非常感谢!很奇怪,我从来没有听说过meteor.js中有这个“fixture”文件……
  • 我的想法来自Discover Meteor。只是为了澄清;文件本身并不特殊。 Meteor 首先加载 lib 目录,然后加载其他所有内容,包括您的 server 目录。
  • 是的,我知道,但是很多人使用“fixture”作为这个文件的名称,它可能已经成为一个小标准:)
猜你喜欢
  • 2014-11-12
  • 2016-09-09
  • 2012-04-23
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 2016-11-30
  • 1970-01-01
相关资源
最近更新 更多