Creating a Foreign Key relationship in Mongoose

node.jsMongodbMongoose

node.js Problem Overview


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);

node.js Solutions


Solution 1 - node.js

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondevtest654987View Question on Stackoverflow
Solution 1 - node.jsTimView Answer on Stackoverflow