【问题标题】:Meteor Autoform, collection hooks - How to insert into user profile array after a collection insert?Meteor Autoform,集合挂钩 - 如何在集合插入后插入用户配置文件数组?
【发布时间】:2016-06-08 18:06:06
【问题描述】:

我正在尝试在自动表单插入另一个集合 (Meteor.users) 后插入用户配置文件数组。

我的简单模式数组是这样设置的 - (在配置文件架构内)

listings: {
type: [String],
optional: true
},
"listings.$.id": {
type: String,
optional: true
}

这是我的集合挂钩方法,应该在列出插入后插入。

//Add listing to user collection on submit
Listings.after.insert(function(userId, doc) {
console.log("STUFF");
Meteor.users.update({_id : userId},
{
    $push :
    {
        'profile.listings.$.id' : this._id 
    }
}

在我看来,这应该可行。表单在没有集合挂钩的情况下正确插入,但现在当我提交表单时,我在 JS 控制台中收到此错误:

错误:过滤掉不在模式中的键后,您的修饰符现在为空(...)

console.log("stuff") 触发,我在报错前的控制台中看到了。

有人对如何做到这一点有任何想法吗?

编辑 - 通过将其切换为修复了一些问题:

Listings.after.insert(function(userId, doc) {
console.log("STUFF" + userId + '     ' + this._id);
Meteor.users.update({_id: userId },
{
    $set :
    {
        "profile.listings.$.id" : this._id 
    }
}

) });

现在由于 $ 运算符,我无法插入到数组中。

【问题讨论】:

    标签: arrays mongodb meteor meteor-autoform meteor-collection-hooks


    【解决方案1】:

    假设列表只是带有 id 字段的对象数组,您可以这样做:

    listings: {
      type: [Object],
      optional: true
    },
    "listings.$.id": {
      type: String,
      optional: true
    }
    
    Listings.after.insert(function(userId, doc) {
      var id = this._id;
      Meteor.users.update({_id: userId }, {
        $push : {
            "profile.listings" : { id: id }
        }
      }); 
    });
    

    这会将您的列表从字符串数组更改为对象数组 - 您不能在字符串上拥有 id 属性。然后,这允许您使用相关对象对 profile.listings 数组执行 $push。但是,如果您实际上只是在列表中存储 ID,则可以进一步简化:

    listings: {
      type: [String],
      optional: true
    }
    
    Listings.after.insert(function(userId, doc) {
      var id = this._id;
      Meteor.users.update({_id: userId }, {
        $push : {
            "profile.listings" : id
        }
      }); 
    });
    

    也许您遗漏了一些代码,但对于您当前的架构,您不需要任何东西,只需要一个字符串数组 - 不需要 id 属性。

    【讨论】:

    • 马上试一试,非常感谢。
    • 你就是男人!非常感谢,我也在复制我使用个人资料图片架构的方式。
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 2014-11-12
    • 2015-04-03
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多