【问题标题】:Does MongoDB support the concept of a compound key?MongoDB 是否支持复合键的概念?
【发布时间】:2012-05-20 14:29:52
【问题描述】:

假设我有如下用户架构

var User = new db.Schema({
    username    : {type: String, unique: true}
    , password    : String
    , email: String
});

为了适应有朋友的用户,我正在考虑修改架构如下

var User = new db.Schema({
    username    : {type: String, unique: true}
    , password    : String
    , email: String
    , friends: [?]
});

我正在考虑对数据库进行非规范化以加快查询速度,而不仅仅是存储 ObjectId。假设现在我只想将 ObjectId 和 username 存储在 friends 数组中。有没有可能做类似的事情

friends: [{String, String}]

这两个字符串代表 ObjectId 和用户名?我不想创建全新的架构,因为我不需要新的 ObjectId。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    当然你可以这样做,但我真的建议给字段命名,比如(在 Mongo shell 语法中):

    user = {
        '_id' : ObjectId(....),
        'username' : 'derick',
        'password' : 'notmypw',
        'email' : 'nospam@example.com',
        'friends' : [
            { 'id': ObjectId(....), 'username' : 'adam' },
            { 'id': ObjectId(....), 'username' : 'ross' },
        ]
    };
    

    但是,您(当然)根本不必存储 ObjectId,因为您的 username 已经是唯一的。哎呀,您甚至可以将用户的用户名设置为 _id 字段的 ID:

    user = {
        '_id' : 'derick',
        'password' : 'notmypw',
        'email' : 'nospam@example.com',
        'friends' : [
            { 'username' : 'adam' },
            { 'username' : 'ross' },
        ]
    };
    

    我认为在 Mongoose 中,您必须这样做(来自 http://mongoosejs.com/docs/model-definition.html 上的“在文档中定义文档”)

    var Friend = new db.Schema({
        username  : String
    });
    
    var User = new db.Schema({
        username    : {type: String, unique: true}
        , password    : String
        , email: String
        , friends: [Friend]
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多