【问题标题】:meteor - How to add a subdocument as reference with SimpleSchema流星 - 如何使用 SimpleSchema 添加子文档作为参考
【发布时间】:2015-12-21 10:36:27
【问题描述】:

我有以下 SimpleSchema

Schema.Team = new SimpleSchema({
    name:{
        type:String
    },
    members: {
        type: [Schema.User],
        optional:true
    }
});

我想(在服务器上)插入一个包含当前用户的新团队文档,作为参考(而不是嵌入文档)。

我试过了:

Teams.insert({name:"theName",members:[Meteor.user()]}) // works but insert the user as an embedded doc.

Teams.insert({name:"theName",members:[Meteor.user()._id]}) // Error: 0 must be an object

我也试过两步:

var id = Teams.insert({name:teamName});
Teams.update({ _id: id },{ $push: { 'users': Meteor.user()._id } });

然后又出现一个我不明白的错误:Error: When the modifier option is true, validation object must have at least one operator

那么我怎样才能插入一个引用另一个模式的文档呢?

【问题讨论】:

  • 如果您将 _id 存储给每个用户而不是对象,则您需要将架构调整为 type: [String]
  • 当 autoform 保存这样的文档时,id 是字符串,但架构仍然是 User.Schema
  • 这就是它无法更新的原因。它试图在架构需要一个对象的地方保存一个字符串。

标签: meteor simple-schema


【解决方案1】:

如果您只想在 Team 集合中存储 userIds 数组,请尝试:

Schema.Team = new SimpleSchema({
    name:{
        type:String
    },
    members: {
        type: [String],
        optional:true
    }
});

然后

Teams.insert({ name: "theName", members: [Meteor.userId()] });

应该可以。稍后当你想添加一个额外的 id 时,你可以:

Teams.update({ _id: teamId },{ $addToSet: { members: Meteor.userId() }});

【讨论】:

  • 更喜欢 $addToSet ,因为它只在不存在的情况下添加一个值。在这种情况下似乎更合适,其中团队成员应该是一组唯一的用户 ID
  • 谢谢,我明白了,但有些事情仍然让我感到困惑:如果我对 Autoform 做同样的事情(假设使用模板中的快速表单,并在其中粘贴 id 的文本输入)它可以工作。
【解决方案2】:

假设您也使用AutoForm,以下可能是您所追求的语法。

如果您使用的是collection2,您还可以在创建团队时添加一个自动值,以便自动将创建者添加到该团队中以更加方便。

Schema.Team = new SimpleSchema({
  name: {
    type:String
  },
  members: {
    type: [String],
    defaultValue: [],
    allowedValues: function () {
      // only allow references to the user collection.
      return Meteor.users.find().map(function (doc) {
        return doc._id
      });
    },
    autoform: {
      // if using autoform, this will display their username as the option instead of their id.
      options: function () {
        return Meteor.users.find().map(function (doc) {
          return {
            value: doc._id,
            label: doc.username // or something
          }
        })
      }
    },
    autoValue: function () {
      if (this.isInsert && !this.isFromTrustedCode) {
        return [this.userId];
      }
    }
  }
});

【讨论】:

    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 2013-12-21
    • 2019-08-14
    • 2021-01-17
    相关资源
    最近更新 更多