自定义模式types在mongoose
我是MongoDB的新手,正在开发一个专业networking项目,在这个项目中,我必须区分Schema中同一个字段的ObjectId
。 假设我有
架构:
TestSchema = new Schema({ Invitation: { from: [ type: schema.types.objectid, ref: 'User' ] } });
Invitation
可以是不同的types,如活动邀请,邀请LinkedIn等连接请求,或邀请现场会议或讨论。 现在,如果我遵循上面的模式,那么不同types的邀请的ObjectId
将被存储在相同的字段中from
从而不会通用并且难以获取或区分哪个ObjectId
属于哪个邀请types。 就像以防万一,如果我把它们存储在一个单一的数组[]
,我想要使该数组中的每个ObjectId
易于区分。 例如:-
{ Invitation: { from: [Objectid(A), Objectid(B), Objectid(C)] } }
假设A
属于活动邀请, B
& C
属于不同types的邀请。 上面的例子是我提出的逻辑。 我也考虑过使用子数组字段或不同的邀请types的子文档,但我认为应该有一个通用的方式来做到这一点。 我花了相当多的时间在谷歌寻找定制objectid概念的逻辑,并不确定这个概念是否有用的,我想在这里。
尽可能多的我理解你的问题,你应该创build用户或事件types架构如:
EventType = new Schema(){ type: String, eventID: { type: Schema.Types.ObjectId ref: 'User'} }
并通过创buildEventType对象在服务器端轻松访问
var eventType = new EventType(); eventType.type = 'event' eventType.eventID = //ObjectId of event doc
@BatScreambuild议你应该在你的User
架构中放置一个“type”字段。
var User = new Schema({ username: ... ... type: String });
这样你就可以区分(和存储 )引用的User
模式中的types。
TestSchema.findById(xxx, function(err, test){ test.invitation.from[0].type == user.type });
但是,如果我正确理解你的用例,我认为你的邀请type
实际上是你的User
和Invitation
(它存储在TestSchema
(不pipe是什么))之间的关系。 如果是这样,你可能不希望在User
存储type
。 也许把它存储在Invitation
本身…
TestSchema = new Schema({ Invitation: { from: [{ type: String, user: { type: schema.types.ObjectId, ref: 'User' } }] } });
所以你可以区分(和存储 )你的TestSchema
的types
TestSchema.findById(xxx, function(err, test){ test.invitation.from[0].type == 'event' ?? test.invitation.from[0].user == 'user' ... });
另外,甚至可能是无关紧要的 ,但是Neo4j非常适合处理这些数据。 因为用户和邀请函之间的“ 关系 ” 本身就是你可以存储types的一个实体 。