首页 文章

mongoose中的自定义架构类型

提问于
浏览
2

我是MongoDB的新手,正在开发一个专业网络项目,我必须区分Schema中相同字段的 ObjectId . 比方说我有

Schema:

TestSchema = new Schema({
    Invitation: {
        from: [
            type: schema.types.objectid,
            ref: 'User'
        ]
    }
});

Invitation 可以是不同类型,例如活动邀请,连接请求邀请,如LinkedIn,或邀请参加现场 Session 或讨论 . 现在,如果我遵循上述模式,那么不同类型的邀请的_965401将被存储在相同的字段 from 中,这不是通用的,并且难以获取或区分 ObjectId 属于哪个邀请类型 . 就像我将它们存储在单个数组_965404中的情况一样,我想让该数组中的每个 ObjectId 易于区分 . 例如:-

{
    Invitation: {
        from: [Objectid(A), Objectid(B), Objectid(C)]
    }
}

假设 A 属于事件邀请, BC 属于不同类型的邀请 . 上面的例子是我提出的逻辑 . 我还考虑使用子数组字段或子文档用于不同的邀请类型,但我认为应该有一种通用的方法 . 我花了相当多的时间在谷歌寻找 custom objectid 概念的逻辑,并不确定这个概念是否对我想要的东西有用 .

2 回答

  • 0

    我理解你的问题,你应该创建用户或事件类型Schema,如:

    EventType = new Schema(){
    type: String,
    eventID: {
    type: Schema.Types.ObjectId
    ref: 'User'}
    }
    

    并通过创建EventType对象轻松访问服务器端

    var eventType = new EventType();
    eventType.type = 'event'
    eventType.eventID = //ObjectId of event doc
    
  • 1

    @BatScream建议您在 User 架构中放置一个"type"字段 .

    var User = new Schema({
        username: ...
        ...
    
        type: String        
    
    });
    

    这样您就可以区分(并存储)引用的 User 模式中的类型 .

    TestSchema.findById(xxx, function(err, test){
        test.invitation.from[0].type == user.type
    });
    

    但如果我理解你的用例,我认为你的 type 邀请实际上是你的 UserInvitation 之间的关系(它存储在 TestSchema (无论是什么)) . 如果's so, you probably wouldn' t想要在 User 中存储 type . 也许把它存放在 Invitation 本身......

    TestSchema = new Schema({
        Invitation: {
            from: [{
                type: String,
                user: {
                    type: schema.types.ObjectId,
                    ref: 'User'
                }
            }]
        }
    });
    

    这样你就可以区分(和存储) TestSchema 中的类型

    TestSchema.findById(xxx, function(err, test){
        test.invitation.from[0].type == 'event' ??
        test.invitation.from[0].user == 'user' ...
    });
    

    此外,甚至可能是偏离主题,但Neo4j非常适合处理此类数据 . 因为User -and-> Invitation之间的“关系”本身就是一个可以存储类型的实体 .

相关问题