I didn't find any tutorials or specification on how to create a polymorphic item on mongodb.
To be clear I want to have an item with a type field, and more fields would be linked in accords to the type of the item. For example Item can be a book or a magazine. The two item have a lot in common but needs also specific fields.
So I was wondering about the best way to do it:
const itemSchema = new Schema({
cuid: { type: 'String', required: true },
name: { type: 'String', required: true },
_t: { type: 'String', required: true },
_t_id: { type: Type.ObjectId, required: true },
category: { type: 'String', required: true },
description: { type: 'String', required: true },
c_at: { type: 'Date', default: Date.now, required: true }, // Created_at
c_by: { type: 'String', default: "me", required: true }, // Created_by
u_at: { type: 'Date', default: Date.now, required: true }, // Updtaed_at
});
Where _t is the type of item and _t_id is the id of the object. I'll then do different schemas for different type and retrieve information this way.
Is it a good solution, is there a better way ? And retrieving data might be difficult :
db.[item._t].find(item._t_id)
If you have any link or any better idea than this, I'll be glad to have your advise. Thanks for your help.
via A. K. Robert
No comments:
Post a Comment