流星方法函数 return 不工作

meteor methods functions return is not working

我正在尝试如果我的数据被删除然后显示 return "removed successfully"; 但它不起作用也没有删除数据。如果我没有使用函数,那么数据将被删除但不会得到任何 return 结果表单回调

正常工作

  Meteor.methods({
        removeFAV: function(userID, product_id) {
            Favorites.remove(
                { user_id: userID, product_id: product_id },
                { multi: true }
            );
        }
    });

没用

Meteor.methods({
        removeFAV: function(userID, product_id) {
           Favorites.remove(
                ({ user_id: userID, product_id: product_id }, { multi: true }),
                function(err) {
                    if (err) {
                        return err;
                    } else {
                        return "removed successfully";
                    }
                }
            );
        }
    });

Meteor Mongo.Collection 不是本机 Mongo 集合,而是将本机 Mongo 调用集成到 Meteor 环境中的包装器。

参见:https://docs.meteor.com/api/collections.html#Mongo-Collection

除非您提供回调,否则 insert updateremove 方法具有特定的阻塞行为:

On the server, if you don’t provide a callback, then remove blocks until the database acknowledges the write and then returns the number of removed documents, or throws an exception if something went wrong.

If you do provide a callback, remove returns immediately. Once the remove completes, the callback is called with a single error argument in the case of failure, or a second argument indicating the number of removed documents if the remove was successful.

https://docs.meteor.com/api/collections.html#Mongo-Collection-remove

由于阻塞式调用是自动抛出enerror,理论上不需要显式处理异常:

Meteor.methods({
    removeFAV: function(userID, product_id) {
        const removedDocs = Favorites.remove(
            { user_id: userID, product_id: product_id },
            { multi: true });
        // remove returns the number of docs being removed
        return `removed [${removedDocs}] document(s) successfully`
    }
});

这样的方法将 return 在 Meteor.call 的回调中,要么将抛出的错误作为第一个参数,要么将结果作为第二个参数。

然而,处理异常并让方法静默失败也是有意义的:

Meteor.methods({
    removeFAV: function(userID, product_id) {
        let removedDocs = 0
        try {
            // remove returns the number of docs being removed
            removedDocs = Favorites.remove(
             { user_id: userID, product_id: product_id },
             { multi: true });
        } catch (e) {
            // log error
            myErrorLog.log(e)
        } finally {
            return `removed [${removedDocs}] document(s) successfully`
        }
    }
});

这永远不会 return 客户端出错,但会在服务器上记录错误。