MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Creazione di una relazione di chiave esterna in Mongoose

Controlla il codice aggiornato di seguito, in particolare questa parte:{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);

Per salvare:

var r = new Recipe();

r.name = 'Blah';
r.ingredients.push('mongo id of ingredient');

r.save();