首页 文章

在Meteor允许功能中更新文档

提问于
浏览
0

我有Messages集合,我删除了不安全的包 . 我想在集合中插入新文档 . 是否可以在插入之前更新当前文档?

这个例子当然不起作用:

Messages.allow({
    insert: function(userID, doc) {

        if (userID == doc.userID) {
            // something like this
            doc = {
                email: Meteor.user().emails[0].address,
                message: doc.message,
                time: Date.now()
            }
            return true;
        } else {
            return false;
        }
    }
});

正如您所看到的,我只是从客户端获得了 doc.message . 但我想将时间和用户的电子邮件保存到文档中 . 我怎么能在流星中这样做?方法是唯一的选择吗?

2 回答

  • 1

    你可以这样做,但你需要使用 deny ,因为不能保证给定的 allow 运行 . 尝试一下:

    Posts.deny({insert: function(userId, doc) {
      if (userId === doc.userID) {
        _.defaults(doc, {
          email: Meteor.user().emails[0].address,
          time: Date.now()
        });
      }
      return false;
    }});
    

    请查看this以获取完整说明 .

  • 2

    使用collection-hooks包可能更合适:https://github.com/matb33/meteor-collection-hooks

    它允许您在另一个集合的另一个插入之前或之后插入文档 .

    例如

    Messages.before.insert(function (userId, doc) {
        doc.createdAt = Date.now();
        doc.xxx = false;
    });
    

相关问题