Mongoid + rails 4 - 实施 User & Following:嵌入式模型的唯一性验证

Mongoid + rails 4 - implementing User & Following: uniquness validation of embedded model

我正在使用 Rails 4.2.1 和 Mongoid 4.0.0

我有一个 User 模型,它嵌入了 Following 模型。我想要达到的效果是:

{
    username:  # This is the id
    ...
    followings: [
        {
            _id:
            username:
            datetime:
        }
    ]
}

我不希望 followings 包含具有相同用户名的条目。如何实现?

我试过两种方法:

  1. 我将 validates :username, presence: true, uniqueness: true 放在 Following 模型的代码中。但是这个验证是全局的——如果我有 John 和 Sam 作为两个用户,并且 John 关注 Sam,那么当 Sam 想要关注 John 时,就会出现重复错误。

  2. 我在User模型中添加了一个索引:

    index ({ 'followings.username': 1 }, { unique: true, drop_dups: true }) 这种方法的问题是,当我创建一个用户 John 时,他的以下字段将有一个用户名 null,然后如果我创建一个用户 Sam,则会抛出一个错误,因为 null用户名重复:

    E11000 duplicate key error index: myapp_development.users.$followings.username_1 dup key: { : null }

非常感谢任何帮助

好吧,事实证明,由于碎片问题,这种建模方式 UserFollowing 会导致文档 growing size,并且没有充分利用 'Rich document' 特性,并且会影响性​​能。来自 MongoDB doc:

In general, embedding provides better performance for read operations, as well as the ability to request and retrieve related data in a single database operation. Embedded data models make it possible to update related data in a single atomic write operation.

However, embedding related data in documents may lead to situations where documents grow after creation. With the MMAPv1 storage engine, document growth can impact write performance and lead to data fragmentation.

所以我吸取了教训。以前不够可观。所以我会放弃这种建模方式,将它们分成不同的集合。