node.js 外键猫鼬

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26008555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:54:28  来源:igfitidea点击:

Foreign-key mongoose

node.jsmongodbmongoose

提问by devtest654987

I begin with mongoose and I want to know how to do this type of configuration :

我从猫鼬开始,我想知道如何进行这种类型的配置:

enter image description here

在此处输入图片说明

a recipe got different ingredient

一个食谱有不同的成分

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

回答by Tim

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

检查下面的更新代码,特别是这部分:{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();