【问题标题】:Can't mogodb insert inside a promise chain using meteormongodb 不能使用流星插入承诺链中
【发布时间】:2017-02-21 19:50:21
【问题描述】:

在遇到障碍时需要帮助。

我正在使用基于 Promise 的 npm 包来获取慈善数据。这个包是基于 Promise 的,所以我使用 Promise 链来解析和获取数据。这一切运作良好。我能够创建一个soap客户端,搜索数据,获取数据,将数据解析成一个准备写入mongo db的对象数组,但问题在于最后一步。

如果我在最终的 .then() 中将一个示例对象写入数据库,它会卡住/停止,甚至不会返回错误。我可以在承诺链开始之前写入数据库,但不能在内部写入。我更喜欢使用原生 Promises 而不是任何外部库。我在这里错过了什么?

// dummy data
const test = {
    CharityName: 'test'
};

Meteor.startup(function() {
    // init the db here.
    console.log(`Meteor started`);
    console.log(Charities.find().count());

    // *1 Charities.insert(test);

    if (Charities.find().count() === 0) {
        console.log('dbs is empty');
        ccAPI.createClient(ccAPIUrl)
            .then(function(client) {

                // *2 Charities.insert(test);

                console.log('searching for charitites');
                return GetCharitiesByKeywordList(client, { APIKey }, ["searchTerm"]);
        })
        .then(function(obj) {
            console.log('fetching all charities');
            const { client, res } = obj;
            return fetchAllCharities(client, { APIKey }, res);
        })
        .then(function(val) {
            console.log(`parse returned data with makeData()`);
            return makeData(val);
        })
        .then(function(val) {
            console.log(`writing objects to db`);

            // *3 Charities.insert(test);

        })
        .catch(function(error) {
            throw error;
        });
}
});

*1 有效,但 *2 & *3 似乎挂起代码的进度。库调用的细节无关紧要,重要的是我无法从承诺链中写入数据库。

【问题讨论】:

  • 如果返回 Charities.insert() 的值是否会抛出错误?是Meteor code must always run within a Fiber吗?
  • @JeremyS。没有发现错误。

标签: mongodb meteor promise


【解决方案1】:

这里的诀窍是按照流星 API 文档和论坛上的 this 解释使用 Collection.rawCollection()

所以现在这行有效:

Charities.rawCollection().insert(test);

【讨论】:

  • 我正要发帖.....你确定没有吞下错误吗? .catch(function(error) { throw error; }); 只是传递错误,因此您需要添加 console.log(error)(或在 Meteor.startup 的调用者中记录错误)。出于好奇,这会导致记录 Charities.insert(test) 错误吗?
  • @Roamer-1888 很好,当我实际控制台时,错误是看到 [错误:流星代码必须始终在光纤中运行。尝试使用 Meteor.bindEnvironment 包装您传递给非 Meteor 库的回调。] 但不是当我只是 Meteor.error(error)throw error 时。该错误消息没有用,文档也不够清晰,无法避免此问题。不得不使用 rawCollection() 感觉有点 hacky。我在回调中尝试了bindEnvironment,但这对我不起作用。
  • 啊哈,至少这证实了@JeremyS. 的“纤维”理论。大约一年前,我为某个项目阅读了 Meteor 光纤,并且必须承认我很快就忘记了所有这些。我需要回归基础以提供进一步的建议。
猜你喜欢
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多