Friday, 11 September 2015

mongoose Foreign-key




var AppSchema = new Schema({
  // _id: String,
  displayName: String
},


One way:

var IssueSchema = new Schema({
  appId: {type: Schema.Types.ObjectId, ref: 'App'},  FK
  contactName: String,
  date: Date
},

Another way:

var IssueSchema = new Schema({
  appId: String,  FK
  contactName: String,
  date: Date
},


But the second one can not give you the relationship.

The first one will give your the relationship. All below code will use the first way.


Normally, if you query issues, you will get "appid" as a string (something like this: "appId" : "55d352e3cd1d6008116e5c2a")

if you want to know app information, then you can use populate:

Issue.find().populate('appId').exec(function (err, issues) {
   .......
  });
};

Then you can get:




That will populate all fields of APP, if you just want populate some of the fields, you can do this:

Issue.find().populate('appId', 'displayName').exec(function (err, issues) {....

Then you can get:




http://mongoosejs.com/docs/populate.html


http://stackoverflow.com/questions/26008555/foreign-key-mongoose


No comments:

Post a comment