MongoDB是否支持复合键的概念?

时间:2012-05-12 03:06:53

标签: mongodb mongoose

假设我有一个用户Schema,如下所示

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: [?]
});

我不是仅仅存储ObjectIds,而是考虑对数据库进行非规范化以便更快地进行查询。假设我现在只想将FriendsId和用户名存储在friends数组中。是否可以做类似

的事情
friends: [{String, String}]

哪两个字符串代表ObjectId和用户名?我不想创建一个全新的模式,因为我不需要新的ObjectId。

1 个答案:

答案 0 :(得分:3)

当然你可以这样做,但我真的建议命名字段,比如(在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]
});
相关问题