簡體   English   中英

如何將其他字段添加到用戶文檔(不在配置文件中)?

[英]How to add additional fields to user documents (not in profile)?

我知道向用戶集合添加數據的經典方法是在profile數組中,但是根據本文檔 ,這不是存儲數據的最佳方法。

是否有替代方法,例如在用戶集合的根目錄中使用默認字段( _idusername等)在同一級別創建一個字段?

您可以通過accountsServer.onCreateUser(func)函數向用戶文檔中添加其他字段。

例如:

if (Meteor.isServer) {
    Accounts.onCreateUser(function(options, user) {
        _.extend(user, {
            myValue: "value",
            myArray: [],
            myObject: {
                key: "value"
            }
        });
    });
}

請注意:默認情況下,以下Meteor.users字段將發布到客戶端usernameemailsprofile 因此,您需要發布任何其他字段。

例如:

if (Meteor.isServer) {
    Meteor.publish("user", function() {
        if (this.userId) return Meteor.users.find({
            _id: this.userId
        }, {
            fields: {
                'myValue': 1,
                'myArray': 1,
                'myObject': 1
            }
        });
        else this.ready();
    });
}

if (Meteor.isClient) {
    Meteor.subscribe("user");
}

profile字段本身沒有任何錯誤,除了用戶可以(當前)默認情況下直接更新自己的個人資料之外。

我不希望這種行為,因為用戶可以在配置文件中存儲任意數據。

如果開發人員將該字段用作授權來源,則可能會帶來真正的安全風險; 例如,將用戶的組或角色存儲在其中。

在這種情況下,用戶可以設置自己的權限和角色。

這是由以下代碼引起的:

users.allow({
  // clients can modify the profile field of their own document, and
  // nothing else.
  update: function (userId, user, fields, modifier) {
    // make sure it is our record
    if (user._id !== userId)
      return false;

    // user can only modify the 'profile' field. sets to multiple
    // sub-keys (eg profile.foo and profile.bar) are merged into entry
    // in the fields list.
    if (fields.length !== 1 || fields[0] !== 'profile')
      return false;

    return true;
  }
});

首先要做的是限制對其的寫入:

Meteor.users.deny({
  update() {
    return true;
  }
});

然后可以使用方法和其他授權代碼對其進行更新。

如果您添加自己的字段並將其發布給當前登錄的用戶,則可以使用自動發布來做到這一點:

Meteor.publish(null, function () {
  if (this.userId) {
    return Meteor.users.find({
      _id: this.userId
    }, {
      fields: {
        yourCustomField1: 1,
        yourCustomField2: 1
      }
    });
  } else {
    return this.ready();
  }
});

Meteor.users只是普通的Mongo.Collection ,因此修改它的方式與其他Collection一樣。 還有一個創建鈎子Accounts.onCreateUser ,它允許您在第一次創建用戶對象時將自定義數據添加到用戶對象中,如@MatthiasEckhart的答案中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM