在Meteor允许功能中更新文档

时间:2014-07-31 20:47:16

标签: mongodb meteor

我有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 个答案:

答案 0 :(得分:2)

最好使用collection-hooks包:https://github.com/matb33/meteor-collection-hooks

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

e.g

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

答案 1 :(得分: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以获取完整说明。

相关问题