Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Foreign Key relationship in Mongoose

I'm beginning with Mongoose and I want to know how to do this type of configuration:

enter image description here

A recipe has different ingredients.

I have my two models:

Ingredient and Recipe:

var mongoose = require('mongoose'); var Schema = mongoose.Schema;  var IngredientSchema = new Schema({     name: String });  module.exports = mongoose.model('Ingredient', IngredientSchema); 
var mongoose = require('mongoose'); var Schema = mongoose.Schema;  var RecipeSchema = new Schema({     name: String });  module.exports = mongoose.model('Recipe', RecipeSchema); 
like image 528
devtest654987 Avatar asked Sep 24 '14 04:09

devtest654987


People also ask

How do mongooses make relationships?

To model relationships between connected data, you can reference a document or embed it in another document as a sub document. Referencing a document does not create a “real” relationship between these two documents as does with a relational database. Referencing documents is also known as normalization.

Is there foreign key in MongoDB?

MongoDB References. Typically, MongoDB doesn't work with the concept of foreign keys. However, relational databases can use foreign keys to visualize data from multiple collections simultaneously.

What is __ V 0 in Mongoose?

This is __v field that is only generated when a document(s) is inserted through mongoose. The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.

What is ref in Mongoose schema?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.


1 Answers

Check Updated code below, in particular this part: {type: Schema.Types.ObjectId, ref: 'Ingredient'}

var mongoose = require('mongoose'); var Schema = mongoose.Schema;  var IngredientSchema = new Schema({     name: String });  module.exports = mongoose.model('Ingredient', IngredientSchema); 
var mongoose = require('mongoose'); var Schema = mongoose.Schema;  var RecipeSchema = new Schema({     name: String,     ingredients:[       {type: Schema.Types.ObjectId, ref: 'Ingredient'}     ] });  module.exports = mongoose.model('Recipe', RecipeSchema); 

To Save:

var r = new Recipe();  r.name = 'Blah'; r.ingredients.push('mongo id of ingredient');  r.save(); 
like image 116
Tim Avatar answered Sep 28 '22 07:09

Tim