Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

mongoid - Association to different entities for a multi-purpose entity in MongoDB?

This question relates to MongoDB with mongoid. My use case is as follows:

I have an Address entity that can be used in many different contexts, e.g. it could be the address of a customer, vendor, user, etc. In addition to that, a customer, for example, can have multiple addresses, such as an office address, a delivery address, and more.

Here is the Address entity, for example:

class Address
    include Mongoid::Document
    field :suburb, type: String
    field :city, type: String
    field :postcode, type: String
    field :country, type: String    
end

From the customer side, my thinking is that I would have the following:

class Customer
    include Mongoid::Document

    has_many :customer_addresses
end

class CustomerAddress
    include Mongoid::Document

    field :address_type, type: String
    has_one :address

    belongs_to :customer
    
end

According to the mongoid documentation, I need to put a belongs_to macro into Address to point back to the CustomerAddress entity for it to work properly.

However, Address, in this case, is multi-purpose. It could also be a vendor address, user address, or belong to any other entity that needs an address.

Perhaps I am thinking too much in terms of relational databases? What is the MongoDB approach for solving this problem?

Secondly, if I didn't want a CustomerAddress entity, but wanted different fields on Customer, such as :office_address and :delivery_address, each resolving to an Address, how would I do that?

question from:https://stackoverflow.com/questions/65879613/association-to-different-entities-for-a-multi-purpose-entity-in-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See https://docs.mongodb.com/mongoid/master/tutorials/mongoid-relations/#polymorphism for handling multiple classes using an address.

CustomerAddress as a separate collection is likely not the best choice for MongoDB, look into embedding.

Use class_name option when the name of the association differs from the name of the class implementing it, which you'd need to have multiple associations of the same class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...