DanyNsg
DanyNsg

Reputation: 355

Relationships by _id in MongoDB

I have been studying MongoDb to migrate my project to MEAN technologies and I have in my database two collections person where I put all basic information like name, age, etc and account where I put information like email, pass, level. I need to create a relationship between that collections. What I did was set account's _id equals to person' _id. Is that correct ?

Person Collection

{
    "_id" : ObjectId("569c39684e23c75303a0fe32"),
    "name" : {
            "First" : "Daniel Alessandro",
            "Last" : "Aguilar Chombo"
    },
    "area" : 1
}

Account Collection

{
        "_id" : ObjectId("569c39684e23c75303a0fe32"),
        "email" : "[email protected]",
        "password" : "testPassword4218",
        "level" : 0
}

Upvotes: 0

Views: 3177

Answers (2)

zangw
zangw

Reputation: 48366

The $ref may used here, to build the relationship between User and Account.

Take mongoose as example:

var personSchema = Schema({
  name    : { First: String, Last: String},
  area    : Number,
  account : [{ type: Schema.Types.ObjectId, ref: 'Account' }]
});

 var accountSchema = Schema({{
        email : String,
        password : String,
        level : Number
}

Upvotes: 1

Ely
Ely

Reputation: 11152

Hmmm, that would be a 1:1 relationship and I would ask why not having the data in one collection then.

You can however simply add a field (or array) of type ObjectID to one collection and store the id_s of the other collection. It simulates a classical foreign key relationship as we know it from RDBMS.

Upvotes: 0

Related Questions