Meteor Autoform,集合挂钩 - 如何在集合插入后插入用户配置文件数组?

时间:2016-02-25 19:13:02

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

在autoform插入另一个集合(Meteor.users)后,我试图插入用户配置文件数组。

我的简单架构数组设置如下 - (在配置文件架构内)

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

这是我的collection-hook方法,应该在列出插入后插入。

//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 
    }
}

) });

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

1 个答案:

答案 0 :(得分: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属性。

相关问题